package com.supermarket.ui;

import com.supermarket.model.User;
import com.supermarket.model.Promotion;
import com.supermarket.model.Product;
import com.supermarket.dao.ProductDAO;
import com.supermarket.dao.SalesDAO;
import com.supermarket.dao.PromotionDAO;
import com.supermarket.dao.UserDAO;
import com.supermarket.dao.ExpiringProductDAO;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Date;
import java.util.List;

/**
 * 管理员主界面
 * 提供商品管理、库存管理、促销管理、统计查询等功能
 */
public class AdminMainFrame extends JFrame {

    private User currentUser;
    private ProductDAO productDAO;
    private SalesDAO salesDAO;
    private PromotionDAO promotionDAO;
    private UserDAO userDAO;
    private ExpiringProductDAO expiringProductDAO;

    // 主面板
    private JTabbedPane tabbedPane;
    private JLabel statusLabel;
    private JLabel userInfoLabel;

    // 商品管理面板
    private JTable productTable;
    private DefaultTableModel productTableModel;
    private JTextField searchField;
    private JButton searchButton, addProductButton, editProductButton, deleteProductButton;

    // 库存管理面板
    private JTable inventoryTable;
    private DefaultTableModel inventoryTableModel;
    private JButton lowStockAlertButton, updateInventoryButton, expiringApprovalButton;

    // 销售统计面板
    private JTable salesTable;
    private DefaultTableModel salesTableModel;
    private JComboBox<String> periodComboBox;
    private JButton queryButton;
    private JLabel totalSalesLabel;

    // 促销管理面板
    private JTable promotionTable;
    private DefaultTableModel promotionTableModel;
    private JComboBox<String> statusFilterCombo;
    private JComboBox<String> typeFilterCombo;

    // 用户管理面板
    private JTable userTable;
    private DefaultTableModel userTableModel;

    public AdminMainFrame(User user) {
        this.currentUser = user;
        this.productDAO = new ProductDAO();
        this.salesDAO = new SalesDAO();
        this.promotionDAO = new PromotionDAO();
        this.userDAO = new UserDAO();
        this.expiringProductDAO = new ExpiringProductDAO();

        initializeComponents();
        setupLayout();
        setupEventListeners();
        setFrameProperties();
        loadInitialData();
    }

    /**
     * 初始化组件
     */
    private void initializeComponents() {
        // 创建现代化选项卡面板
        tabbedPane = new JTabbedPane();
        tabbedPane.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        tabbedPane.setBackground(Color.WHITE);
        tabbedPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 状态栏
        statusLabel = new JLabel("系统就绪");
        statusLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        statusLabel.setForeground(new Color(108, 117, 125));

        userInfoLabel = new JLabel("当前用户：" + currentUser.getRealName() + " (" + currentUser.getRoleName() + ")");
        userInfoLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        userInfoLabel.setForeground(new Color(52, 58, 64));

        // 初始化各个功能面板
        initProductManagementPanel();
        initInventoryManagementPanel();
        initSalesStatisticsPanel();
        initPromotionManagementPanel();
        initUserManagementPanel();
    }

    /**
     * 初始化商品管理面板
     */
    private void initProductManagementPanel() {
        JPanel productPanel = new JPanel(new BorderLayout());
        productPanel.setBackground(Color.WHITE);
        productPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        // 顶部操作面板
        JPanel topPanel = createStyledPanel();
        topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));

        // 搜索区域
        JPanel searchPanel = createStyledPanel();
        searchPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));

        JLabel searchLabel = new JLabel("搜索商品：");
        searchLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        searchLabel.setForeground(new Color(73, 80, 87));

        searchField = new JTextField(25);
        searchField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        searchField.setBorder(createModernBorder());
        searchField.setPreferredSize(new Dimension(250, 35));

        searchButton = createStyledButton("搜索", new Color(74, 144, 226));

        searchPanel.add(searchLabel);
        searchPanel.add(searchField);
        searchPanel.add(searchButton);

        // 操作按钮区域
        JPanel buttonPanel = createStyledPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));

        addProductButton = createStyledButton("添加商品", new Color(40, 167, 69));
        editProductButton = createStyledButton("编辑商品", new Color(255, 193, 7));
        deleteProductButton = createStyledButton("删除商品", new Color(220, 53, 69));
        JButton refreshProductButton = createStyledButton("刷新", new Color(108, 117, 125));

        buttonPanel.add(addProductButton);
        buttonPanel.add(editProductButton);
        buttonPanel.add(deleteProductButton);
        buttonPanel.add(refreshProductButton);

        topPanel.add(searchPanel);
        topPanel.add(Box.createVerticalStrut(10));
        topPanel.add(buttonPanel);

        // 商品表格
        String[] productColumns = { "编号", "商品编码", "商品名称", "类别", "供应商", "单位", "进价", "售价", "库存", "状态" };
        productTableModel = new DefaultTableModel(productColumns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 表格不可编辑
            }
        };
        productTable = createStyledTable(productTableModel);

        JScrollPane productScrollPane = new JScrollPane(productTable);
        productScrollPane.setBorder(BorderFactory.createLineBorder(new Color(220, 220, 220)));
        productScrollPane.getViewport().setBackground(Color.WHITE);

        // 添加刷新按钮事件监听器
        refreshProductButton.addActionListener(e -> loadProductData());

        productPanel.add(topPanel, BorderLayout.NORTH);
        productPanel.add(productScrollPane, BorderLayout.CENTER);

        tabbedPane.addTab("商品管理", productPanel);
    }

    /**
     * 初始化库存管理面板
     */
    private void initInventoryManagementPanel() {
        JPanel inventoryPanel = new JPanel(new BorderLayout());
        inventoryPanel.setBackground(Color.WHITE);
        inventoryPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        // 操作面板
        JPanel operationPanel = createStyledPanel();
        operationPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));

        lowStockAlertButton = createStyledButton("低库存预警", new Color(255, 193, 7));
        updateInventoryButton = createStyledButton("库存盘点", new Color(108, 117, 125));
        expiringApprovalButton = createStyledButton("临期审批", new Color(220, 53, 69));
        JButton exportButton = createStyledButton("导出库存", new Color(40, 167, 69));
        JButton refreshInventoryButton = createStyledButton("刷新", new Color(74, 144, 226));

        operationPanel.add(lowStockAlertButton);
        operationPanel.add(updateInventoryButton);
        operationPanel.add(expiringApprovalButton);
        operationPanel.add(exportButton);
        operationPanel.add(refreshInventoryButton);

        // 库存表格
        String[] inventoryColumns = { "商品编码", "商品名称", "类别", "当前库存", "最小库存", "最大库存", "库存状态", "最后销售日期" };
        inventoryTableModel = new DefaultTableModel(inventoryColumns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        inventoryTable = createStyledTable(inventoryTableModel);

        // 设置库存状态列的颜色渲染器
        inventoryTable.getColumnModel().getColumn(6)
                .setCellRenderer((table, value, isSelected, hasFocus, row, column) -> {
                    JLabel label = new JLabel(value != null ? value.toString() : "");
                    label.setOpaque(true);

                    if (!isSelected) {
                        if ("缺货".equals(value)) {
                            label.setBackground(new Color(255, 200, 200));
                            label.setForeground(Color.RED);
                        } else if ("低库存".equals(value)) {
                            label.setBackground(new Color(255, 255, 200));
                            label.setForeground(new Color(200, 100, 0));
                        } else {
                            label.setBackground(Color.WHITE);
                            label.setForeground(Color.BLACK);
                        }
                    } else {
                        label.setBackground(table.getSelectionBackground());
                        label.setForeground(table.getSelectionForeground());
                    }

                    return label;
                });

        JScrollPane inventoryScrollPane = new JScrollPane(inventoryTable);
        inventoryScrollPane.setBorder(BorderFactory.createLineBorder(new Color(220, 220, 220)));
        inventoryScrollPane.getViewport().setBackground(Color.WHITE);

        // 添加刷新按钮事件监听器
        refreshInventoryButton.addActionListener(e -> loadInventoryData());

        inventoryPanel.add(operationPanel, BorderLayout.NORTH);
        inventoryPanel.add(inventoryScrollPane, BorderLayout.CENTER);

        tabbedPane.addTab("库存管理", inventoryPanel);
    }

    /**
     * 初始化销售统计面板
     */
    private void initSalesStatisticsPanel() {
        JPanel salesPanel = new JPanel(new BorderLayout());
        salesPanel.setBackground(Color.WHITE);
        salesPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        // 查询面板
        JPanel queryPanel = createStyledPanel();
        queryPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));

        JLabel periodLabel = new JLabel("统计周期：");
        periodLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        periodLabel.setForeground(new Color(73, 80, 87));

        periodComboBox = new JComboBox<>(new String[] { "今日", "本周", "本月", "自定义" });
        periodComboBox.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        periodComboBox.setPreferredSize(new Dimension(120, 35));

        queryButton = createStyledButton("查询统计", new Color(74, 144, 226));
        JButton refreshSalesButton = createStyledButton("刷新", new Color(40, 167, 69));

        totalSalesLabel = new JLabel("总销售额: ¥0.00");
        totalSalesLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
        totalSalesLabel.setForeground(new Color(220, 53, 69));

        queryPanel.add(periodLabel);
        queryPanel.add(periodComboBox);
        queryPanel.add(queryButton);
        queryPanel.add(refreshSalesButton);
        queryPanel.add(Box.createHorizontalStrut(50));
        queryPanel.add(totalSalesLabel);

        // 销售统计表格
        String[] salesColumns = { "收银员ID", "收银员姓名", "订单数量", "销售总额", "折扣总额", "实收金额", "平均订单金额" };
        salesTableModel = new DefaultTableModel(salesColumns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        salesTable = createStyledTable(salesTableModel);

        JScrollPane salesScrollPane = new JScrollPane(salesTable);
        salesScrollPane.setBorder(BorderFactory.createLineBorder(new Color(220, 220, 220)));
        salesScrollPane.getViewport().setBackground(Color.WHITE);

        // 添加刷新按钮事件监听器
        refreshSalesButton.addActionListener(e -> querySalesStatistics());

        salesPanel.add(queryPanel, BorderLayout.NORTH);
        salesPanel.add(salesScrollPane, BorderLayout.CENTER);

        tabbedPane.addTab("销售统计", salesPanel);
    }

    /**
     * 初始化促销管理面板
     */
    private void initPromotionManagementPanel() {
        JPanel promotionPanel = new JPanel(new BorderLayout());
        promotionPanel.setBackground(Color.WHITE);
        promotionPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        // 顶部操作面板
        JPanel topPanel = createStyledPanel();
        topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));

        // 促销活动操作区域
        JPanel actionPanel = createStyledPanel();
        actionPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));

        JButton addPromotionButton = createStyledButton("新建促销", new Color(40, 167, 69));
        JButton editPromotionButton = createStyledButton("编辑促销", new Color(255, 193, 7));
        JButton deletePromotionButton = createStyledButton("删除促销", new Color(220, 53, 69));
        JButton startPromotionButton = createStyledButton("启动促销", new Color(74, 144, 226));
        JButton stopPromotionButton = createStyledButton("停止促销", new Color(108, 117, 125));

        actionPanel.add(addPromotionButton);
        actionPanel.add(editPromotionButton);
        actionPanel.add(deletePromotionButton);
        actionPanel.add(startPromotionButton);
        actionPanel.add(stopPromotionButton);

        // 筛选区域
        JPanel filterPanel = createStyledPanel();
        filterPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));

        JLabel statusLabel = new JLabel("状态筛选：");
        statusLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        statusLabel.setForeground(new Color(73, 80, 87));

        statusFilterCombo = new JComboBox<>(new String[] { "全部", "待启动", "进行中", "已结束", "已取消" });
        statusFilterCombo.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        statusFilterCombo.setPreferredSize(new Dimension(120, 35));

        JLabel typeLabel = new JLabel("类型筛选：");
        typeLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        typeLabel.setForeground(new Color(73, 80, 87));

        typeFilterCombo = new JComboBox<>(new String[] { "全部", "折扣", "满减", "买赠" });
        typeFilterCombo.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        typeFilterCombo.setPreferredSize(new Dimension(120, 35));

        JButton refreshButton = createStyledButton("刷新", new Color(108, 117, 125));

        filterPanel.add(statusLabel);
        filterPanel.add(statusFilterCombo);
        filterPanel.add(Box.createHorizontalStrut(20));
        filterPanel.add(typeLabel);
        filterPanel.add(typeFilterCombo);
        filterPanel.add(Box.createHorizontalStrut(20));
        filterPanel.add(refreshButton);

        topPanel.add(actionPanel);
        topPanel.add(Box.createVerticalStrut(10));
        topPanel.add(filterPanel);

        // 促销活动表格
        String[] promotionColumns = {
                "编号", "促销编码", "促销名称", "促销类型", "开始时间", "结束时间",
                "优惠规则", "状态", "创建人", "创建时间"
        };

        promotionTableModel = new DefaultTableModel(promotionColumns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        promotionTable = createStyledTable(promotionTableModel);

        JScrollPane promotionScrollPane = new JScrollPane(promotionTable);
        promotionScrollPane.setBorder(BorderFactory.createLineBorder(new Color(220, 220, 220)));
        promotionScrollPane.getViewport().setBackground(Color.WHITE);

        // 设置事件监听器
        setupPromotionEventListeners(addPromotionButton, editPromotionButton, deletePromotionButton,
                startPromotionButton, stopPromotionButton, promotionTable, refreshButton);

        promotionPanel.add(topPanel, BorderLayout.NORTH);
        promotionPanel.add(promotionScrollPane, BorderLayout.CENTER);

        tabbedPane.addTab("促销管理", promotionPanel);
    }

    /**
     * 设置布局
     */
    private void setupLayout() {
        setLayout(new BorderLayout());
        setBackground(Color.WHITE);

        // 顶部信息栏
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBackground(new Color(248, 249, 250));
        topPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(220, 220, 220)),
                BorderFactory.createEmptyBorder(15, 20, 15, 20)));

        JLabel titleLabel = new JLabel("超市管理系统 - 管理员控制台");
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 18));
        titleLabel.setForeground(new Color(52, 58, 64));

        topPanel.add(titleLabel, BorderLayout.WEST);
        topPanel.add(userInfoLabel, BorderLayout.EAST);

        // 底部状态栏
        JPanel statusPanel = new JPanel(new BorderLayout());
        statusPanel.setBackground(new Color(248, 249, 250));
        statusPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(220, 220, 220)),
                BorderFactory.createEmptyBorder(10, 20, 10, 20)));
        statusPanel.add(statusLabel, BorderLayout.WEST);

        JButton logoutButton = createStyledButton("注销", new Color(220, 53, 69));
        logoutButton.addActionListener(e -> logout());
        statusPanel.add(logoutButton, BorderLayout.EAST);

        // 主面板
        add(topPanel, BorderLayout.NORTH);
        add(tabbedPane, BorderLayout.CENTER);
        add(statusPanel, BorderLayout.SOUTH);
    }

    /**
     * 设置事件监听器
     */
    private void setupEventListeners() {
        // 搜索商品
        searchButton.addActionListener(e -> searchProducts());
        searchField.addActionListener(e -> searchProducts());

        // 商品管理按钮
        addProductButton.addActionListener(e -> showAddProductDialog());
        editProductButton.addActionListener(e -> showEditProductDialog());
        deleteProductButton.addActionListener(e -> deleteSelectedProduct());

        // 库存管理按钮
        lowStockAlertButton.addActionListener(e -> showLowStockAlert());
        updateInventoryButton.addActionListener(e -> showInventoryUpdateDialog());
        expiringApprovalButton.addActionListener(e -> showExpiringProductApprovalDialog());

        // 销售统计按钮
        queryButton.addActionListener(e -> querySalesStatistics());
    }

    /**
     * 设置窗口属性
     */
    private void setFrameProperties() {
        setTitle("超市管理系统 - 管理员控制台");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1200, 800);
        setLocationRelativeTo(null);
        setBackground(Color.WHITE);
        // 设置现代化的最小尺寸
        setMinimumSize(new Dimension(1000, 700));
        // 启动时最大化窗口
        setExtendedState(JFrame.MAXIMIZED_BOTH);
    }

    /**
     * 加载初始数据
     */
    private void loadInitialData() {
        loadAllProducts();
        loadInventoryData();
        loadTodaySales();
        loadPromotionData();
        setStatus("数据加载完成");
    }

    /**
     * 加载所有商品
     */
    private void loadAllProducts() {
        try {
            productTableModel.setRowCount(0);
            var products = productDAO.getAllProducts();

            for (var product : products) {
                Object[] row = {
                        product.getId(),
                        product.getProductCode(),
                        product.getProductName(),
                        product.getCategoryName(),
                        product.getSupplierName(),
                        product.getUnit(),
                        String.format("%.2f", product.getPurchasePrice()),
                        String.format("%.2f", product.getSalePrice()),
                        product.getCurrentStock(),
                        product.getStockStatus()
                };
                productTableModel.addRow(row);
            }

            setStatus("已加载 " + products.size() + " 个商品");
        } catch (Exception e) {
            showError("加载商品数据失败：" + e.getMessage());
        }
    }

    /**
     * 加载商品数据
     */
    private void loadProductData() {
        try {
            // 从数据库加载商品数据
            List<Product> products = productDAO.getAllProducts();

            // 清空表格
            productTableModel.setRowCount(0);

            // 添加商品数据到表格
            for (Product product : products) {
                Object[] row = {
                        product.getId(),
                        product.getProductCode(),
                        product.getProductName(),
                        product.getCategoryName(),
                        product.getSupplierName(),
                        product.getUnit(),
                        product.getPurchasePrice(),
                        product.getSalePrice(),
                        product.getCurrentStock(),
                        "ACTIVE".equals(product.getStatus()) ? "正常" : "禁用"
                };
                productTableModel.addRow(row);
            }
        } catch (Exception e) {
            showError("加载商品数据失败：" + e.getMessage());
        }
    }

    /**
     * 加载库存数据
     */
    private void loadInventoryData() {
        try {
            inventoryTableModel.setRowCount(0);
            var products = productDAO.getAllProducts();

            for (var product : products) {
                // 格式化最后销售日期
                String lastSaleDateStr = "从未销售";
                if (product.getLastSaleDate() != null) {
                    lastSaleDateStr = product.getLastSaleDate().toString();
                }

                Object[] row = {
                        product.getProductCode(),
                        product.getProductName(),
                        product.getCategoryName(),
                        product.getCurrentStock(),
                        product.getMinStock(),
                        product.getMaxStock(),
                        product.getStockStatus(),
                        lastSaleDateStr
                };
                inventoryTableModel.addRow(row);
            }
        } catch (Exception e) {
            showError("加载库存数据失败：" + e.getMessage());
        }
    }

    /**
     * 加载今日销售额
     */
    private void loadTodaySales() {
        try {
            BigDecimal todaySales = salesDAO.getTodaySales(null);
            totalSalesLabel.setText("今日总销售额: ¥" + String.format("%.2f", todaySales));
        } catch (Exception e) {
            totalSalesLabel.setText("今日总销售额: 数据获取失败");
        }
    }

    /**
     * 加载促销数据
     */
    private void loadPromotionData() {
        try {
            promotionTableModel.setRowCount(0);
            java.util.List<Promotion> promotions = promotionDAO.getAllPromotions();

            for (Promotion promotion : promotions) {
                Object[] row = {
                        promotion.getId(),
                        promotion.getPromotionCode(),
                        promotion.getPromotionName(),
                        promotion.getPromotionTypeDescription(),
                        promotion.getStartDate(),
                        promotion.getEndDate(),
                        promotion.getPromotionRule(),
                        promotion.getStatusDescription(),
                        promotion.getCreatedByName() != null ? promotion.getCreatedByName() : "未知",
                        promotion.getCreatedAt() != null ? promotion.getCreatedAt().toString().substring(0, 19) : ""
                };
                promotionTableModel.addRow(row);
            }

            setStatus("已加载 " + promotions.size() + " 个促销活动");
        } catch (Exception e) {
            showError("加载促销数据失败：" + e.getMessage());
        }
    }

    /**
     * 搜索商品
     */
    private void searchProducts() {
        String keyword = searchField.getText().trim();
        if (keyword.isEmpty()) {
            loadAllProducts();
            return;
        }

        try {
            productTableModel.setRowCount(0);
            var products = productDAO.searchProducts(keyword);

            for (var product : products) {
                Object[] row = {
                        product.getId(),
                        product.getProductCode(),
                        product.getProductName(),
                        product.getCategoryName(),
                        product.getSupplierName(),
                        product.getUnit(),
                        String.format("%.2f", product.getPurchasePrice()),
                        String.format("%.2f", product.getSalePrice()),
                        product.getCurrentStock(),
                        product.getStockStatus()
                };
                productTableModel.addRow(row);
            }

            setStatus("搜索到 " + products.size() + " 个商品");
        } catch (Exception e) {
            showError("搜索商品失败：" + e.getMessage());
        }
    }

    /**
     * 显示添加商品对话框
     */
    private void showAddProductDialog() {
        JDialog dialog = createStyledDialog("添加商品", 900, 700);

        // 主面板
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBackground(new Color(248, 249, 250));

        // 标题面板
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        titlePanel.setBackground(new Color(248, 249, 250));
        JLabel titleLabel = new JLabel("添加新商品", JLabel.CENTER);
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 18));
        titleLabel.setForeground(new Color(52, 144, 220));
        titlePanel.add(titleLabel);
        mainPanel.add(titlePanel, BorderLayout.NORTH);

        // 内容面板 - 使用两列布局
        JPanel contentPanel = new JPanel(new GridBagLayout());
        contentPanel.setBackground(Color.WHITE);
        contentPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                BorderFactory.createEmptyBorder(30, 30, 30, 30)));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 15, 10, 15);
        gbc.anchor = GridBagConstraints.WEST;

        // 左列
        // 商品编码
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        gbc.fill = GridBagConstraints.NONE;
        contentPanel.add(createStyledLabel("商品编码 *"), gbc);
        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        JTextField codeField = createStyledTextField(30);
        contentPanel.add(codeField, gbc);

        // 商品名称
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        contentPanel.add(createStyledLabel("商品名称 *"), gbc);
        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        JTextField nameField = createStyledTextField(30);
        contentPanel.add(nameField, gbc);

        // 类别ID
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        contentPanel.add(createStyledLabel("类别ID *"), gbc);
        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        JSpinner categorySpinner = new JSpinner(new SpinnerNumberModel(1, 1, 999, 1));
        categorySpinner.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                BorderFactory.createEmptyBorder(8, 12, 8, 12)));
        contentPanel.add(categorySpinner, gbc);

        // 供应商ID
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        contentPanel.add(createStyledLabel("供应商ID *"), gbc);
        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        JSpinner supplierSpinner = new JSpinner(new SpinnerNumberModel(1, 1, 999, 1));
        supplierSpinner.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                BorderFactory.createEmptyBorder(8, 12, 8, 12)));
        contentPanel.add(supplierSpinner, gbc);

        // 单位
        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        contentPanel.add(createStyledLabel("单位 *"), gbc);
        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        JTextField unitField = createStyledTextField(30);
        unitField.setText("件");
        contentPanel.add(unitField, gbc);

        // 进价
        gbc.gridx = 0;
        gbc.gridy = 5;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        contentPanel.add(createStyledLabel("进价 *"), gbc);
        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        JTextField purchasePriceField = createStyledTextField(30);
        contentPanel.add(purchasePriceField, gbc);

        // 售价
        gbc.gridx = 0;
        gbc.gridy = 6;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        contentPanel.add(createStyledLabel("售价 *"), gbc);
        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        JTextField salePriceField = createStyledTextField(30);
        contentPanel.add(salePriceField, gbc);

        // 右列
        // 保质期
        gbc.gridx = 2;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        contentPanel.add(createStyledLabel("保质期(天)"), gbc);
        gbc.gridx = 3;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        JSpinner shelfLifeSpinner = new JSpinner(new SpinnerNumberModel(30, 1, 9999, 1));
        shelfLifeSpinner.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                BorderFactory.createEmptyBorder(8, 12, 8, 12)));
        contentPanel.add(shelfLifeSpinner, gbc);

        // 初始库存
        gbc.gridx = 2;
        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        contentPanel.add(createStyledLabel("初始库存"), gbc);
        gbc.gridx = 3;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        JTextField stockField = createStyledTextField(30);
        stockField.setText("0");
        contentPanel.add(stockField, gbc);

        // 最小库存
        gbc.gridx = 2;
        gbc.gridy = 2;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        contentPanel.add(createStyledLabel("最小库存"), gbc);
        gbc.gridx = 3;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        JTextField minStockField = createStyledTextField(30);
        minStockField.setText("10");
        contentPanel.add(minStockField, gbc);

        // 最大库存
        gbc.gridx = 2;
        gbc.gridy = 3;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        contentPanel.add(createStyledLabel("最大库存"), gbc);
        gbc.gridx = 3;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        JTextField maxStockField = createStyledTextField(30);
        maxStockField.setText("1000");
        contentPanel.add(maxStockField, gbc);

        // 描述 - 跨两列
        gbc.gridx = 0;
        gbc.gridy = 7;
        gbc.gridwidth = 4;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        contentPanel.add(createStyledLabel("描述"), gbc);
        gbc.gridy = 8;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        JTextArea descArea = createStyledTextArea(4, 40);
        contentPanel.add(new JScrollPane(descArea), gbc);

        mainPanel.add(contentPanel, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 0));
        buttonPanel.setBackground(new Color(248, 249, 250));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(20, 0, 20, 0));

        JButton saveButton = createStyledButton("保存", new Color(40, 167, 69));
        JButton cancelButton = createStyledButton("取消", new Color(108, 117, 125));

        saveButton.addActionListener(e -> {
            if (saveNewProduct(codeField, nameField, categorySpinner, supplierSpinner,
                    unitField, purchasePriceField, salePriceField, shelfLifeSpinner,
                    descArea, stockField, minStockField, maxStockField)) {
                dialog.dispose();
                loadAllProducts(); // 重新加载数据
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        dialog.add(mainPanel);
        dialog.setVisible(true);
    }

    /**
     * 保存新商品
     */
    private boolean saveNewProduct(JTextField codeField, JTextField nameField, JSpinner categorySpinner,
            JSpinner supplierSpinner, JTextField unitField, JTextField purchasePriceField,
            JTextField salePriceField, JSpinner shelfLifeSpinner, JTextArea descArea,
            JTextField stockField, JTextField minStockField, JTextField maxStockField) {
        try {
            // 验证输入
            String code = codeField.getText().trim();
            String name = nameField.getText().trim();
            String unit = unitField.getText().trim();
            String purchasePriceStr = purchasePriceField.getText().trim();
            String salePriceStr = salePriceField.getText().trim();
            String stockStr = stockField.getText().trim();
            String minStockStr = minStockField.getText().trim();
            String maxStockStr = maxStockField.getText().trim();

            if (code.isEmpty() || name.isEmpty() || unit.isEmpty() ||
                    purchasePriceStr.isEmpty() || salePriceStr.isEmpty()) {
                showError("请填写所有必填字段！");
                return false;
            }

            // 检查商品编码是否已存在
            if (productDAO.isProductCodeExists(code)) {
                showError("商品编码已存在，请使用其他编码！");
                return false;
            }

            // 创建商品对象
            Product product = new Product();
            product.setProductCode(code);
            product.setProductName(name);
            product.setCategoryId((Integer) categorySpinner.getValue());
            product.setSupplierId((Integer) supplierSpinner.getValue());
            product.setUnit(unit);
            product.setPurchasePrice(new BigDecimal(purchasePriceStr));
            product.setSalePrice(new BigDecimal(salePriceStr));
            product.setShelfLifeDays((Integer) shelfLifeSpinner.getValue());
            product.setDescription(descArea.getText().trim());

            // 设置库存信息
            product.setCurrentStock(new BigDecimal(stockStr));
            product.setMinStock(new BigDecimal(minStockStr));
            product.setMaxStock(new BigDecimal(maxStockStr));

            // 保存到数据库
            if (productDAO.addProduct(product)) {
                showInfo("商品添加成功！");
                return true;
            } else {
                showError("商品添加失败，请检查数据库连接！");
                return false;
            }

        } catch (NumberFormatException e) {
            showError("请输入正确的数字格式！");
            return false;
        } catch (Exception e) {
            showError("保存商品失败：" + e.getMessage());
            return false;
        }
    }

    /**
     * 显示编辑商品对话框
     */
    private void showEditProductDialog() {
        int selectedRow = productTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要编辑的商品！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        try {
            int productId = (Integer) productTableModel.getValueAt(selectedRow, 0);
            Product product = productDAO.getProductById(productId);

            if (product == null) {
                showError("获取商品信息失败！");
                return;
            }

            // 创建编辑对话框 - 使用两列布局
            JDialog dialog = createStyledDialog("编辑商品", 900, 700);

            // 主面板
            JPanel mainPanel = new JPanel(new BorderLayout());
            mainPanel.setBackground(new Color(248, 249, 250));

            // 标题面板
            JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
            titlePanel.setBackground(new Color(248, 249, 250));
            JLabel titleLabel = new JLabel("编辑商品信息", JLabel.CENTER);
            titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 18));
            titleLabel.setForeground(new Color(52, 144, 220));
            titlePanel.add(titleLabel);
            mainPanel.add(titlePanel, BorderLayout.NORTH);

            // 内容面板 - 使用两列布局
            JPanel contentPanel = new JPanel(new GridBagLayout());
            contentPanel.setBackground(Color.WHITE);
            contentPanel.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                    BorderFactory.createEmptyBorder(30, 30, 30, 30)));

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(10, 15, 10, 15);
            gbc.anchor = GridBagConstraints.WEST;

            // 左列
            // 商品编码（编辑时不允许更改）
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.gridwidth = 1;
            gbc.fill = GridBagConstraints.NONE;
            contentPanel.add(createStyledLabel("商品编码"), gbc);
            gbc.gridx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            JLabel codeLabel = new JLabel(product.getProductCode());
            codeLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
            codeLabel.setForeground(new Color(73, 80, 87));
            codeLabel.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                    BorderFactory.createEmptyBorder(8, 12, 8, 12)));
            codeLabel.setBackground(new Color(248, 249, 250));
            codeLabel.setOpaque(true);
            contentPanel.add(codeLabel, gbc);

            // 商品名称
            gbc.gridx = 0;
            gbc.gridy = 1;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            contentPanel.add(createStyledLabel("商品名称 *"), gbc);
            gbc.gridx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            JTextField nameField = createStyledTextField(30);
            nameField.setText(product.getProductName());
            contentPanel.add(nameField, gbc);

            // 类别ID
            gbc.gridx = 0;
            gbc.gridy = 2;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            contentPanel.add(createStyledLabel("类别ID *"), gbc);
            gbc.gridx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            JSpinner categorySpinner = new JSpinner(new SpinnerNumberModel(product.getCategoryId(), 1, 999, 1));
            categorySpinner.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                    BorderFactory.createEmptyBorder(8, 12, 8, 12)));
            contentPanel.add(categorySpinner, gbc);

            // 供应商ID
            gbc.gridx = 0;
            gbc.gridy = 3;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            contentPanel.add(createStyledLabel("供应商ID *"), gbc);
            gbc.gridx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            JSpinner supplierSpinner = new JSpinner(new SpinnerNumberModel(product.getSupplierId(), 1, 999, 1));
            supplierSpinner.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                    BorderFactory.createEmptyBorder(8, 12, 8, 12)));
            contentPanel.add(supplierSpinner, gbc);

            // 单位
            gbc.gridx = 0;
            gbc.gridy = 4;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            contentPanel.add(createStyledLabel("单位 *"), gbc);
            gbc.gridx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            JTextField unitField = createStyledTextField(30);
            unitField.setText(product.getUnit());
            contentPanel.add(unitField, gbc);

            // 进价
            gbc.gridx = 0;
            gbc.gridy = 5;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            contentPanel.add(createStyledLabel("进价 *"), gbc);
            gbc.gridx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            JTextField purchasePriceField = createStyledTextField(30);
            purchasePriceField.setText(product.getPurchasePrice().toString());
            contentPanel.add(purchasePriceField, gbc);

            // 售价
            gbc.gridx = 0;
            gbc.gridy = 6;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            contentPanel.add(createStyledLabel("售价 *"), gbc);
            gbc.gridx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            JTextField salePriceField = createStyledTextField(30);
            salePriceField.setText(product.getSalePrice().toString());
            contentPanel.add(salePriceField, gbc);

            // 右列
            // 保质期
            gbc.gridx = 2;
            gbc.gridy = 0;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            contentPanel.add(createStyledLabel("保质期(天)"), gbc);
            gbc.gridx = 3;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            JSpinner shelfLifeSpinner = new JSpinner(new SpinnerNumberModel(
                    product.getShelfLifeDays() != null ? product.getShelfLifeDays() : 30, 1, 9999, 1));
            shelfLifeSpinner.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                    BorderFactory.createEmptyBorder(8, 12, 8, 12)));
            contentPanel.add(shelfLifeSpinner, gbc);

            // 当前库存
            gbc.gridx = 2;
            gbc.gridy = 1;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            contentPanel.add(createStyledLabel("当前库存"), gbc);
            gbc.gridx = 3;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            JTextField stockField = createStyledTextField(30);
            stockField.setText(product.getCurrentStock().toString());
            contentPanel.add(stockField, gbc);

            // 最小库存
            gbc.gridx = 2;
            gbc.gridy = 2;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            contentPanel.add(createStyledLabel("最小库存"), gbc);
            gbc.gridx = 3;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            JTextField minStockField = createStyledTextField(30);
            minStockField.setText(product.getMinStock().toString());
            contentPanel.add(minStockField, gbc);

            // 最大库存
            gbc.gridx = 2;
            gbc.gridy = 3;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            contentPanel.add(createStyledLabel("最大库存"), gbc);
            gbc.gridx = 3;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            JTextField maxStockField = createStyledTextField(30);
            maxStockField.setText(product.getMaxStock().toString());
            contentPanel.add(maxStockField, gbc);

            // 描述 - 跨两列
            gbc.gridx = 0;
            gbc.gridy = 7;
            gbc.gridwidth = 4;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            contentPanel.add(createStyledLabel("描述"), gbc);
            gbc.gridy = 8;
            gbc.fill = GridBagConstraints.BOTH;
            gbc.weightx = 1.0;
            gbc.weighty = 1.0;
            JTextArea descArea = createStyledTextArea(4, 40);
            descArea.setText(product.getDescription() != null ? product.getDescription() : "");
            contentPanel.add(new JScrollPane(descArea), gbc);

            mainPanel.add(contentPanel, BorderLayout.CENTER);

            // 按钮面板
            JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 0));
            buttonPanel.setBackground(new Color(248, 249, 250));
            buttonPanel.setBorder(BorderFactory.createEmptyBorder(20, 0, 20, 0));

            JButton saveButton = createStyledButton("保存", new Color(40, 167, 69));
            JButton cancelButton = createStyledButton("取消", new Color(108, 117, 125));

            saveButton.addActionListener(e -> {
                if (updateProduct(product, nameField, categorySpinner, supplierSpinner,
                        unitField, purchasePriceField, salePriceField, shelfLifeSpinner,
                        descArea, stockField, minStockField, maxStockField)) {
                    dialog.dispose();
                    loadAllProducts(); // 重新加载数据
                }
            });

            cancelButton.addActionListener(e -> dialog.dispose());

            buttonPanel.add(saveButton);
            buttonPanel.add(cancelButton);
            mainPanel.add(buttonPanel, BorderLayout.SOUTH);

            dialog.add(mainPanel);
            dialog.setVisible(true);

        } catch (Exception e) {
            showError("打开编辑对话框失败：" + e.getMessage());
        }
    }

    /**
     * 更新商品信息
     */
    private boolean updateProduct(Product product, JTextField nameField, JSpinner categorySpinner,
            JSpinner supplierSpinner, JTextField unitField, JTextField purchasePriceField,
            JTextField salePriceField, JSpinner shelfLifeSpinner, JTextArea descArea,
            JTextField stockField, JTextField minStockField, JTextField maxStockField) {
        try {
            // 验证输入
            String name = nameField.getText().trim();
            String unit = unitField.getText().trim();
            String purchasePriceStr = purchasePriceField.getText().trim();
            String salePriceStr = salePriceField.getText().trim();
            String stockStr = stockField.getText().trim();
            String minStockStr = minStockField.getText().trim();
            String maxStockStr = maxStockField.getText().trim();

            if (name.isEmpty() || unit.isEmpty() || purchasePriceStr.isEmpty() || salePriceStr.isEmpty()) {
                showError("请填写所有必填字段！");
                return false;
            }

            // 更新商品对象
            product.setProductName(name);
            product.setCategoryId((Integer) categorySpinner.getValue());
            product.setSupplierId((Integer) supplierSpinner.getValue());
            product.setUnit(unit);
            product.setPurchasePrice(new BigDecimal(purchasePriceStr));
            product.setSalePrice(new BigDecimal(salePriceStr));
            product.setShelfLifeDays((Integer) shelfLifeSpinner.getValue());
            product.setDescription(descArea.getText().trim());

            // 更新库存信息
            product.setCurrentStock(new BigDecimal(stockStr));
            product.setMinStock(new BigDecimal(minStockStr));
            product.setMaxStock(new BigDecimal(maxStockStr));

            // 保存到数据库
            boolean productUpdated = productDAO.updateProduct(product);
            boolean inventoryUpdated = productDAO.updateInventory(
                    product.getId(),
                    product.getCurrentStock(),
                    product.getMinStock(),
                    product.getMaxStock());

            if (productUpdated && inventoryUpdated) {
                showInfo("商品更新成功！");
                return true;
            } else {
                showError("商品更新失败，请检查数据库连接！");
                return false;
            }

        } catch (NumberFormatException e) {
            showError("请输入正确的数字格式！");
            return false;
        } catch (Exception e) {
            showError("更新商品失败：" + e.getMessage());
            return false;
        }
    }

    /**
     * 删除选中的商品
     */
    private void deleteSelectedProduct() {
        int selectedRow = productTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要删除的商品！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        int confirm = JOptionPane.showConfirmDialog(this, "确定要删除选中的商品吗？", "确认删除",
                JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            try {
                int productId = (Integer) productTableModel.getValueAt(selectedRow, 0);
                boolean success = productDAO.deleteProduct(productId);

                if (success) {
                    loadAllProducts();
                    loadInventoryData();
                    showInfo("商品删除成功");
                } else {
                    showError("商品删除失败");
                }
            } catch (Exception e) {
                showError("删除商品失败：" + e.getMessage());
            }
        }
    }

    /**
     * 显示低库存预警
     */
    private void showLowStockAlert() {
        try {
            var lowStockProducts = productDAO.getLowStockProducts();

            if (lowStockProducts.isEmpty()) {
                JOptionPane.showMessageDialog(this, "当前没有低库存商品！", "库存预警",
                        JOptionPane.INFORMATION_MESSAGE);
            } else {
                StringBuilder message = new StringBuilder("以下商品库存不足：\n\n");
                for (var product : lowStockProducts) {
                    message.append(String.format("• %s (%s) - 当前库存: %s, 最小库存: %s\n",
                            product.getProductName(),
                            product.getProductCode(),
                            product.getCurrentStock(),
                            product.getMinStock()));
                }

                JOptionPane.showMessageDialog(this, message.toString(), "库存预警",
                        JOptionPane.WARNING_MESSAGE);
            }
        } catch (Exception e) {
            showError("获取库存预警失败：" + e.getMessage());
        }
    }

    /**
     * 显示库存更新对话框
     */
    private void showInventoryUpdateDialog() {
        JDialog dialog = createStyledDialog("库存盘点", 1000, 700);

        // 主面板
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBackground(new Color(248, 249, 250));

        // 标题面板
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        titlePanel.setBackground(new Color(248, 249, 250));
        JLabel titleLabel = new JLabel("库存盘点", JLabel.CENTER);
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 18));
        titleLabel.setForeground(new Color(52, 144, 220));
        titlePanel.add(titleLabel);
        mainPanel.add(titlePanel, BorderLayout.NORTH);

        // 内容面板
        JPanel contentPanel = new JPanel(new BorderLayout());
        contentPanel.setBackground(Color.WHITE);
        contentPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                BorderFactory.createEmptyBorder(20, 20, 20, 20)));

        // 创建库存盘点表格
        String[] columns = { "商品编码", "商品名称", "当前库存", "盘点数量", "差异", "备注" };
        DefaultTableModel inventoryModel = new DefaultTableModel(columns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return column >= 3; // 只有盘点数量和备注可编辑
            }
        };

        JTable inventoryTable = createStyledTable(inventoryModel);
        inventoryTable.setRowHeight(35);
        inventoryTable.getTableHeader().setFont(new Font("Microsoft YaHei", Font.BOLD, 13));
        inventoryTable.getTableHeader().setBackground(new Color(52, 144, 220));
        inventoryTable.getTableHeader().setForeground(Color.BLACK);

        // 加载商品数据
        try {
            var products = productDAO.getAllProducts();
            for (var product : products) {
                Object[] row = {
                        product.getProductCode(),
                        product.getProductName(),
                        product.getCurrentStock(),
                        product.getCurrentStock(), // 默认盘点数量等于当前库存
                        0, // 差异
                        "" // 备注
                };
                inventoryModel.addRow(row);
            }
        } catch (Exception e) {
            showError("加载商品数据失败：" + e.getMessage());
        }

        // 添加表格变化监听器
        inventoryTable.getModel().addTableModelListener(e -> {
            if (e.getColumn() == 3) { // 盘点数量列
                int row = e.getFirstRow();
                BigDecimal currentStock = (BigDecimal) inventoryModel.getValueAt(row, 2);
                BigDecimal countStock = new BigDecimal(inventoryModel.getValueAt(row, 3).toString());
                BigDecimal difference = countStock.subtract(currentStock);
                inventoryModel.setValueAt(difference, row, 4);
            }
        });

        JScrollPane scrollPane = new JScrollPane(inventoryTable);
        scrollPane.setBorder(BorderFactory.createLineBorder(new Color(220, 220, 220), 1));
        contentPanel.add(scrollPane, BorderLayout.CENTER);

        mainPanel.add(contentPanel, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 0));
        buttonPanel.setBackground(new Color(248, 249, 250));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(20, 0, 20, 0));

        JButton saveButton = createStyledButton("保存盘点结果", new Color(40, 167, 69));
        JButton cancelButton = createStyledButton("取消", new Color(108, 117, 125));

        saveButton.addActionListener(e -> {
            try {
                // 这里应该保存盘点结果到数据库
                showInfo("库存盘点结果已保存！");
                dialog.dispose();
                loadInventoryData(); // 重新加载库存数据
            } catch (Exception ex) {
                showError("保存盘点结果失败：" + ex.getMessage());
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        dialog.add(mainPanel);
        dialog.setVisible(true);
    }

    /**
     * 查询销售统计
     */
    private void querySalesStatistics() {
        String period = (String) periodComboBox.getSelectedItem();

        try {
            // 获取查询日期范围
            Date startDate, endDate;
            java.util.Date today = new java.util.Date();

            switch (period) {
                case "今日":
                    startDate = endDate = new Date(today.getTime());
                    break;
                case "本周":
                    // 简化处理，使用过去7天
                    startDate = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000L);
                    endDate = new Date(today.getTime());
                    break;
                case "本月":
                    // 简化处理，使用过去30天
                    startDate = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000L);
                    endDate = new Date(today.getTime());
                    break;
                default:
                    startDate = endDate = new Date(today.getTime());
            }

            // 查询销售统计数据
            salesTableModel.setRowCount(0);
            var statistics = salesDAO.getSalesStatistics(startDate, endDate, null);

            BigDecimal totalAmount = BigDecimal.ZERO;

            for (var stat : statistics) {
                Object[] row = {
                        stat[0], // cashier_id
                        stat[1], // cashier_name
                        stat[2], // order_count
                        String.format("%.2f", (BigDecimal) stat[3]), // total_amount
                        String.format("%.2f", (BigDecimal) stat[4]), // total_discount
                        String.format("%.2f", (BigDecimal) stat[5]), // final_amount
                        String.format("%.2f", (BigDecimal) stat[6]) // avg_order_amount
                };
                salesTableModel.addRow(row);
                totalAmount = totalAmount.add((BigDecimal) stat[5]);
            }

            totalSalesLabel.setText(period + "总销售额: ¥" + String.format("%.2f", totalAmount));
            setStatus("已查询 " + period + " 销售统计");

            // 显示详细统计信息
            showDetailedStatistics(period, statistics, totalAmount);

        } catch (Exception e) {
            showError("查询销售统计失败：" + e.getMessage());
        }
    }

    /**
     * 显示详细统计信息
     */
    private void showDetailedStatistics(String period, List<Object[]> statistics, BigDecimal totalAmount) {
        JDialog statsDialog = new JDialog(this, "详细销售统计 - " + period, true);
        statsDialog.setSize(700, 600);
        statsDialog.setLocationRelativeTo(this);

        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 统计概览面板
        JPanel overviewPanel = new JPanel(new GridBagLayout());
        overviewPanel.setBorder(BorderFactory.createTitledBorder("统计概览"));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;

        // 计算统计数据
        int totalOrders = statistics.stream().mapToInt(stat -> ((Number) stat[2]).intValue()).sum();
        BigDecimal totalDiscount = statistics.stream()
                .map(stat -> (BigDecimal) stat[4])
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal avgOrderAmount = totalOrders > 0
                ? totalAmount.divide(new BigDecimal(totalOrders), 2, RoundingMode.HALF_UP)
                : BigDecimal.ZERO;

        // 添加统计信息
        String[] labels = { "统计期间", "总销售额", "总订单数", "平均订单金额", "总折扣金额", "收银员数量" };
        String[] values = {
                period,
                "¥" + String.format("%.2f", totalAmount),
                String.valueOf(totalOrders),
                "¥" + String.format("%.2f", avgOrderAmount),
                "¥" + String.format("%.2f", totalDiscount),
                String.valueOf(statistics.size())
        };

        for (int i = 0; i < labels.length; i++) {
            gbc.gridx = 0;
            gbc.gridy = i;
            overviewPanel.add(new JLabel(labels[i] + "："), gbc);

            gbc.gridx = 1;
            JLabel valueLabel = new JLabel(values[i]);
            valueLabel.setFont(new Font("微软雅黑", Font.BOLD, 12));
            valueLabel.setForeground(new Color(40, 167, 69));
            overviewPanel.add(valueLabel, gbc);
        }

        // 收银员业绩表格
        String[] columns = { "收银员", "订单数", "销售额", "折扣金额", "实收金额", "平均订单金额" };
        DefaultTableModel detailModel = new DefaultTableModel(columns, 0);

        for (Object[] stat : statistics) {
            Object[] row = {
                    stat[1], // 收银员姓名
                    stat[2], // 订单数
                    String.format("%.2f", (BigDecimal) stat[3]), // 销售额
                    String.format("%.2f", (BigDecimal) stat[4]), // 折扣金额
                    String.format("%.2f", (BigDecimal) stat[5]), // 实收金额
                    String.format("%.2f", (BigDecimal) stat[6]) // 平均订单金额
            };
            detailModel.addRow(row);
        }

        JTable detailTable = createStyledTable(detailModel);
        JScrollPane scrollPane = new JScrollPane(detailTable);

        // 创建选项卡
        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.addTab("统计概览", overviewPanel);
        tabbedPane.addTab("收银员业绩", scrollPane);

        panel.add(tabbedPane, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout());
        JButton exportButton = createStyledButton("导出报表", new Color(40, 167, 69));
        JButton closeButton = createStyledButton("关闭", new Color(108, 117, 125));

        exportButton.addActionListener(e -> {
            exportSalesReport(period, statistics, totalAmount);
        });

        closeButton.addActionListener(e -> statsDialog.dispose());

        buttonPanel.add(exportButton);
        buttonPanel.add(closeButton);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        statsDialog.add(panel);
        statsDialog.setVisible(true);
    }

    /**
     * 注销登录
     */
    private void logout() {
        int confirm = JOptionPane.showConfirmDialog(this, "确定要注销登录吗？", "确认注销",
                JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            dispose();
            new LoginFrame().setVisible(true);
        }
    }

    /**
     * 设置状态信息
     */
    private void setStatus(String status) {
        statusLabel.setText(status);
    }

    /**
     * 显示错误信息
     */
    private void showError(String message) {
        JOptionPane.showMessageDialog(this, message, "错误", JOptionPane.ERROR_MESSAGE);
        setStatus("操作失败");
    }

    /**
     * 显示信息提示
     */
    private void showInfo(String message) {
        JOptionPane.showMessageDialog(this, message, "提示", JOptionPane.INFORMATION_MESSAGE);
        setStatus(message);
    }

    // ====================== UI 工具方法 ======================

    /**
     * 创建标准化面板
     */
    private JPanel createStyledPanel() {
        JPanel panel = new JPanel();
        panel.setBackground(Color.WHITE);
        return panel;
    }

    /**
     * 创建现代化按钮
     */
    private JButton createStyledButton(String text, Color backgroundColor) {
        JButton button = new JButton(text);
        button.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        button.setBackground(backgroundColor);
        button.setForeground(new Color(33, 37, 41)); // 统一使用深色文字
        button.setBorder(BorderFactory.createEmptyBorder(8, 16, 8, 16));
        button.setFocusPainted(false);
        button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        return button;
    }

    /**
     * 创建美化弹窗
     */
    private JDialog createStyledDialog(String title, int width, int height) {
        JDialog dialog = new JDialog(this, title, true);
        dialog.setSize(width, height);
        dialog.setLocationRelativeTo(this);
        dialog.getContentPane().setBackground(new Color(248, 249, 250));
        dialog.setResizable(false);

        // 设置窗口图标
        try {
            dialog.setIconImage(createIconImage());
        } catch (Exception e) {
            // 忽略图标设置错误
        }

        return dialog;
    }

    /**
     * 创建美化输入框
     */
    private JTextField createStyledTextField(int columns) {
        JTextField field = new JTextField(columns);
        field.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        field.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                BorderFactory.createEmptyBorder(8, 12, 8, 12)));
        field.setBackground(Color.WHITE);
        field.setForeground(new Color(33, 37, 41));
        return field;
    }

    /**
     * 创建美化文本区域
     */
    private JTextArea createStyledTextArea(int rows, int columns) {
        JTextArea area = new JTextArea(rows, columns);
        area.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        area.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                BorderFactory.createEmptyBorder(8, 12, 8, 12)));
        area.setBackground(Color.WHITE);
        area.setForeground(new Color(33, 37, 41));
        area.setLineWrap(true);
        area.setWrapStyleWord(true);
        return area;
    }

    /**
     * 创建美化标签
     */
    private JLabel createStyledLabel(String text) {
        JLabel label = new JLabel(text);
        label.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        label.setForeground(new Color(73, 80, 87));
        return label;
    }

    /**
     * 创建美化组合框
     */
    private JComboBox<String> createStyledComboBox() {
        JComboBox<String> comboBox = new JComboBox<>();
        comboBox.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        comboBox.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                BorderFactory.createEmptyBorder(6, 10, 6, 10)));
        comboBox.setBackground(Color.WHITE);
        comboBox.setForeground(new Color(33, 37, 41));
        return comboBox;
    }

    /**
     * 创建美化微调器
     */
    private JSpinner createStyledSpinner() {
        JSpinner spinner = new JSpinner();
        spinner.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        spinner.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                BorderFactory.createEmptyBorder(6, 10, 6, 10)));
        spinner.setBackground(Color.WHITE);
        spinner.setForeground(new Color(33, 37, 41));
        return spinner;
    }

    /**
     * 创建图标
     */
    private Image createIconImage() {
        BufferedImage icon = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = icon.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setColor(new Color(52, 144, 220));
        g2d.fillRoundRect(4, 4, 24, 24, 6, 6);
        g2d.setColor(Color.WHITE);
        g2d.setFont(new Font("Arial", Font.BOLD, 16));
        g2d.drawString("S", 8, 20);
        g2d.dispose();
        return icon;
    }

    /**
     * 创建现代化边框
     */
    private javax.swing.border.Border createModernBorder() {
        return BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                BorderFactory.createEmptyBorder(8, 12, 8, 12));
    }

    /**
     * 创建现代化表格
     */
    private JTable createStyledTable(DefaultTableModel model) {
        JTable table = new JTable(model);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        table.getTableHeader().setFont(new Font("Microsoft YaHei", Font.BOLD, 13));
        table.setRowHeight(35);

        // 设置表格样式
        table.setShowGrid(true);
        table.setGridColor(new Color(240, 240, 240));
        table.setSelectionBackground(new Color(74, 144, 226, 50));
        table.setSelectionForeground(new Color(52, 58, 64));

        // 设置表头样式
        table.getTableHeader().setBackground(new Color(248, 249, 250));
        table.getTableHeader().setForeground(new Color(52, 58, 64));
        table.getTableHeader().setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(220, 220, 220)));

        return table;
    }

    /**
     * 初始化用户管理面板
     */
    private void initUserManagementPanel() {
        JPanel userPanel = new JPanel(new BorderLayout());
        userPanel.setBackground(Color.WHITE);
        userPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        // 顶部操作面板
        JPanel topPanel = createStyledPanel();
        topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));

        // 用户管理操作区域
        JPanel actionPanel = createStyledPanel();
        actionPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));

        JButton editUserButton = createStyledButton("编辑用户", new Color(255, 193, 7));
        JButton deleteUserButton = createStyledButton("删除用户", new Color(220, 53, 69));
        JButton resetPasswordButton = createStyledButton("重置密码", new Color(74, 144, 226));
        JButton toggleStatusButton = createStyledButton("启用/禁用", new Color(108, 117, 125));
        JButton refreshUserButton = createStyledButton("刷新", new Color(40, 167, 69));

        actionPanel.add(editUserButton);
        actionPanel.add(deleteUserButton);
        actionPanel.add(resetPasswordButton);
        actionPanel.add(toggleStatusButton);
        actionPanel.add(refreshUserButton);

        // 搜索和筛选区域
        JPanel searchPanel = createStyledPanel();
        searchPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));

        JLabel searchLabel = new JLabel("搜索用户：");
        searchLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        searchLabel.setForeground(new Color(73, 80, 87));

        JTextField userSearchField = new JTextField();
        userSearchField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        userSearchField.setBorder(createModernBorder());
        userSearchField.setPreferredSize(new Dimension(200, 35));

        JButton userSearchButton = createStyledButton("搜索", new Color(74, 144, 226));

        JLabel roleLabel = new JLabel("角色筛选：");
        roleLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        roleLabel.setForeground(new Color(73, 80, 87));

        JComboBox<String> roleFilter = new JComboBox<>(new String[] { "全部", "管理员", "收银员" });
        roleFilter.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        roleFilter.setPreferredSize(new Dimension(120, 35));

        JLabel statusLabel = new JLabel("状态筛选：");
        statusLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        statusLabel.setForeground(new Color(73, 80, 87));

        JComboBox<String> statusFilter = new JComboBox<>(new String[] { "全部", "正常", "禁用" });
        statusFilter.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        statusFilter.setPreferredSize(new Dimension(120, 35));

        searchPanel.add(searchLabel);
        searchPanel.add(userSearchField);
        searchPanel.add(userSearchButton);
        searchPanel.add(Box.createHorizontalStrut(20));
        searchPanel.add(roleLabel);
        searchPanel.add(roleFilter);
        searchPanel.add(Box.createHorizontalStrut(20));
        searchPanel.add(statusLabel);
        searchPanel.add(statusFilter);

        topPanel.add(actionPanel);
        topPanel.add(Box.createVerticalStrut(10));
        topPanel.add(searchPanel);

        // 用户管理表格
        String[] userColumns = {
                "编号", "用户名", "真实姓名", "角色", "电话", "邮箱",
                "状态", "创建时间"
        };

        userTableModel = new DefaultTableModel(userColumns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        userTable = createStyledTable(userTableModel);

        // 从数据库加载用户数据
        loadUserData();

        JScrollPane userScrollPane = new JScrollPane(userTable);
        userScrollPane.setBorder(BorderFactory.createLineBorder(new Color(220, 220, 220)));
        userScrollPane.getViewport().setBackground(Color.WHITE);

        // 设置事件监听器
        setupUserManagementEventListeners(editUserButton, deleteUserButton,
                resetPasswordButton, toggleStatusButton, refreshUserButton, userTable,
                userSearchButton, userSearchField, roleFilter, statusFilter);

        userPanel.add(topPanel, BorderLayout.NORTH);
        userPanel.add(userScrollPane, BorderLayout.CENTER);

        tabbedPane.addTab("用户管理", userPanel);
    }

    /**
     * 设置促销管理事件监听器
     */
    private void setupPromotionEventListeners(JButton addBtn, JButton editBtn, JButton deleteBtn,
            JButton startBtn, JButton stopBtn, JTable table, JButton refreshBtn) {
        // 新建促销
        addBtn.addActionListener(e -> showAddPromotionDialog());

        // 编辑促销
        editBtn.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow >= 0) {
                showEditPromotionDialog(selectedRow);
            } else {
                showInfo("请选择要编辑的促销活动");
            }
        });

        // 删除促销
        deleteBtn.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow >= 0) {
                deletePromotion(selectedRow);
            } else {
                showInfo("请选择要删除的促销活动");
            }
        });

        // 启动促销
        startBtn.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow >= 0) {
                startPromotion(selectedRow);
            } else {
                showInfo("请选择要启动的促销活动");
            }
        });

        // 停止促销
        stopBtn.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow >= 0) {
                stopPromotion(selectedRow);
            } else {
                showInfo("请选择要停止的促销活动");
            }
        });

        // 刷新按钮
        refreshBtn.addActionListener(e -> loadPromotionData());

        // 状态筛选
        statusFilterCombo.addActionListener(e -> filterPromotions());

        // 类型筛选
        typeFilterCombo.addActionListener(e -> filterPromotions());
    }

    /**
     * 根据筛选条件加载促销数据
     */
    private void filterPromotions() {
        try {
            promotionTableModel.setRowCount(0);
            String statusFilter = (String) statusFilterCombo.getSelectedItem();
            String typeFilter = (String) typeFilterCombo.getSelectedItem();

            java.util.List<Promotion> promotions;

            // 根据状态筛选
            if ("全部".equals(statusFilter)) {
                promotions = promotionDAO.getAllPromotions();
            } else {
                String dbStatus = convertStatusToDb(statusFilter);
                promotions = promotionDAO.getPromotionsByStatus(dbStatus);
            }

            // 根据类型进一步筛选
            if (!"全部".equals(typeFilter)) {
                String dbType = convertTypeToDb(typeFilter);
                promotions = promotions.stream()
                        .filter(p -> dbType.equals(p.getPromotionType()))
                        .collect(java.util.stream.Collectors.toList());
            }

            // 显示数据
            for (Promotion promotion : promotions) {
                Object[] row = {
                        promotion.getId(),
                        promotion.getPromotionCode(),
                        promotion.getPromotionName(),
                        promotion.getPromotionTypeDescription(),
                        promotion.getStartDate(),
                        promotion.getEndDate(),
                        promotion.getPromotionRule(),
                        promotion.getStatusDescription(),
                        promotion.getCreatedByName() != null ? promotion.getCreatedByName() : "未知",
                        promotion.getCreatedAt() != null ? promotion.getCreatedAt().toString().substring(0, 19) : ""
                };
                promotionTableModel.addRow(row);
            }

            setStatus("筛选显示 " + promotions.size() + " 个促销活动");
        } catch (Exception e) {
            showError("筛选促销数据失败：" + e.getMessage());
        }
    }

    /**
     * 将界面状态转换为数据库状态
     */
    private String convertStatusToDb(String uiStatus) {
        switch (uiStatus) {
            case "待启动":
                return "PENDING";
            case "进行中":
                return "ACTIVE";
            case "已结束":
                return "EXPIRED";
            case "已取消":
                return "CANCELLED";
            default:
                return uiStatus;
        }
    }

    /**
     * 将界面类型转换为数据库类型
     */
    private String convertTypeToDb(String uiType) {
        switch (uiType) {
            case "折扣":
                return "DISCOUNT";
            case "满减":
                return "FIXED_AMOUNT";
            case "买赠":
                return "BUY_GET";
            default:
                return uiType;
        }
    }

    /**
     * 显示新建促销对话框
     */
    private void showAddPromotionDialog() {
        JDialog dialog = createStyledDialog("新建促销活动", 800, 600);

        // 主面板
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBackground(new Color(248, 249, 250));

        // 标题面板
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        titlePanel.setBackground(new Color(248, 249, 250));
        JLabel titleLabel = new JLabel("新建促销活动", JLabel.CENTER);
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 18));
        titleLabel.setForeground(new Color(52, 144, 220));
        titlePanel.add(titleLabel);
        mainPanel.add(titlePanel, BorderLayout.NORTH);

        // 内容面板 - 使用两列布局
        JPanel contentPanel = new JPanel(new GridBagLayout());
        contentPanel.setBackground(Color.WHITE);
        contentPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                BorderFactory.createEmptyBorder(30, 30, 30, 30)));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 15, 10, 15);
        gbc.anchor = GridBagConstraints.WEST;

        // 左列
        // 促销名称
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        gbc.fill = GridBagConstraints.NONE;
        contentPanel.add(createStyledLabel("促销名称 *"), gbc);
        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        JTextField nameField = createStyledTextField(30);
        contentPanel.add(nameField, gbc);

        // 促销编码
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        contentPanel.add(createStyledLabel("促销编码 *"), gbc);
        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        JTextField codeField = createStyledTextField(30);
        codeField.setText("PROMO" + System.currentTimeMillis() % 100000); // 自动生成编码
        contentPanel.add(codeField, gbc);

        // 促销类型
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        contentPanel.add(createStyledLabel("促销类型 *"), gbc);
        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        JComboBox<String> typeCombo = createStyledComboBox();
        typeCombo.addItem("折扣");
        typeCombo.addItem("满减");
        typeCombo.addItem("买赠");
        contentPanel.add(typeCombo, gbc);

        // 开始日期
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        contentPanel.add(createStyledLabel("开始日期 *"), gbc);
        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        JTextField startDateField = createStyledTextField(30);
        startDateField.setText("2025-09-10");
        contentPanel.add(startDateField, gbc);

        // 结束日期
        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        contentPanel.add(createStyledLabel("结束日期 *"), gbc);
        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        JTextField endDateField = createStyledTextField(30);
        endDateField.setText("2025-12-31");
        contentPanel.add(endDateField, gbc);

        // 右列
        // 折扣率/折扣金额
        gbc.gridx = 2;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        JLabel discountLabel = createStyledLabel("折扣率(%) *");
        contentPanel.add(discountLabel, gbc);
        gbc.gridx = 3;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        JTextField discountField = createStyledTextField(30);
        discountField.setText("90");
        contentPanel.add(discountField, gbc);

        // 最小购买数量
        gbc.gridx = 2;
        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        contentPanel.add(createStyledLabel("最小购买数量"), gbc);
        gbc.gridx = 3;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        JSpinner quantitySpinner = createStyledSpinner();
        quantitySpinner.setModel(new SpinnerNumberModel(1, 1, 999, 1));
        contentPanel.add(quantitySpinner, gbc);

        // 类型变化时更新标签
        typeCombo.addActionListener(e -> {
            String selectedType = (String) typeCombo.getSelectedItem();
            if ("折扣".equals(selectedType)) {
                discountLabel.setText("折扣率(%) *");
                discountField.setText("90"); // 9折
            } else if ("满减".equals(selectedType)) {
                discountLabel.setText("立减金额 *");
                discountField.setText("10.00");
            } else {
                discountLabel.setText("相关参数 *");
                discountField.setText("1");
            }
        });

        mainPanel.add(contentPanel, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 0));
        buttonPanel.setBackground(new Color(248, 249, 250));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(20, 0, 20, 0));

        JButton saveButton = createStyledButton("保存", new Color(40, 167, 69));
        JButton cancelButton = createStyledButton("取消", new Color(108, 117, 125));

        saveButton.addActionListener(e -> {
            if (saveNewPromotion(nameField, codeField, typeCombo, startDateField,
                    endDateField, discountField, quantitySpinner)) {
                dialog.dispose();
                loadPromotionData(); // 重新加载数据
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        dialog.add(mainPanel);
        dialog.setVisible(true);
    }

    /**
     * 保存新的促销活动
     */
    private boolean saveNewPromotion(JTextField nameField, JTextField codeField,
            JComboBox<String> typeCombo, JTextField startDateField,
            JTextField endDateField, JTextField discountField,
            JSpinner quantitySpinner) {
        try {
            // 验证输入
            String name = nameField.getText().trim();
            String code = codeField.getText().trim();
            String type = (String) typeCombo.getSelectedItem();
            String startDateStr = startDateField.getText().trim();
            String endDateStr = endDateField.getText().trim();
            String discountStr = discountField.getText().trim();
            int minQuantity = (Integer) quantitySpinner.getValue();

            if (name.isEmpty() || code.isEmpty() || startDateStr.isEmpty() ||
                    endDateStr.isEmpty() || discountStr.isEmpty()) {
                showError("请填写所有必填字段！");
                return false;
            }

            // 检查编码是否已存在
            if (promotionDAO.isPromotionCodeExists(code)) {
                showError("促销编码已存在，请使用其他编码！");
                return false;
            }

            // 创建促销对象
            Promotion promotion = new Promotion();
            promotion.setPromotionCode(code);
            promotion.setPromotionName(name);
            promotion.setPromotionType(convertTypeToDb(type));
            promotion.setMinQuantity(minQuantity);
            promotion.setCreatedBy(currentUser.getId());

            // 设置日期
            try {
                promotion.setStartDate(java.sql.Date.valueOf(startDateStr));
                promotion.setEndDate(java.sql.Date.valueOf(endDateStr));
            } catch (IllegalArgumentException e) {
                showError("日期格式不正确，请使用格式：YYYY-MM-DD");
                return false;
            }

            // 设置折扣参数
            try {
                BigDecimal discountValue = new BigDecimal(discountStr);
                if ("DISCOUNT".equals(promotion.getPromotionType())) {
                    if (discountValue.compareTo(BigDecimal.ZERO) <= 0 ||
                            discountValue.compareTo(new BigDecimal("100")) > 0) {
                        showError("折扣率必须在0-100之间！");
                        return false;
                    }
                    promotion.setDiscountRate(discountValue);
                } else if ("FIXED_AMOUNT".equals(promotion.getPromotionType())) {
                    if (discountValue.compareTo(BigDecimal.ZERO) <= 0) {
                        showError("立减金额必须大于0！");
                        return false;
                    }
                    promotion.setDiscountAmount(discountValue);
                }
            } catch (NumberFormatException e) {
                showError("折扣参数格式不正确！");
                return false;
            }

            // 保存到数据库
            if (promotionDAO.addPromotion(promotion)) {
                showInfo("促销活动创建成功！");
                return true;
            } else {
                showError("促销活动创建失败，请检查数据库连接！");
                return false;
            }

        } catch (Exception e) {
            showError("保存促销活动失败：" + e.getMessage());
            return false;
        }
    }

    /**
     * 显示编辑促销对话框
     */
    private void showEditPromotionDialog(int selectedRow) {
        try {
            int promotionId = (Integer) promotionTableModel.getValueAt(selectedRow, 0);
            Promotion promotion = promotionDAO.getPromotionById(promotionId);

            if (promotion == null) {
                showError("获取促销活动信息失败！");
                return;
            }

            // 创建编辑对话框 - 使用两列布局
            JDialog dialog = createStyledDialog("编辑促销活动", 800, 600);

            // 主面板
            JPanel mainPanel = new JPanel(new BorderLayout());
            mainPanel.setBackground(new Color(248, 249, 250));

            // 标题面板
            JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
            titlePanel.setBackground(new Color(248, 249, 250));
            JLabel titleLabel = new JLabel("编辑促销活动", JLabel.CENTER);
            titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 18));
            titleLabel.setForeground(new Color(52, 144, 220));
            titlePanel.add(titleLabel);
            mainPanel.add(titlePanel, BorderLayout.NORTH);

            // 内容面板 - 使用两列布局
            JPanel contentPanel = new JPanel(new GridBagLayout());
            contentPanel.setBackground(Color.WHITE);
            contentPanel.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                    BorderFactory.createEmptyBorder(30, 30, 30, 30)));

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(10, 15, 10, 15);
            gbc.anchor = GridBagConstraints.WEST;

            // 左列
            // 促销名称
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.gridwidth = 1;
            gbc.fill = GridBagConstraints.NONE;
            contentPanel.add(createStyledLabel("促销名称 *"), gbc);
            gbc.gridx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            JTextField nameField = createStyledTextField(30);
            nameField.setText(promotion.getPromotionName());
            contentPanel.add(nameField, gbc);

            // 促销类型（编辑时不允许更改）
            gbc.gridx = 0;
            gbc.gridy = 1;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            contentPanel.add(createStyledLabel("促销类型"), gbc);
            gbc.gridx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            JLabel typeLabel = new JLabel(promotion.getPromotionTypeDescription());
            typeLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
            typeLabel.setForeground(new Color(73, 80, 87));
            typeLabel.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                    BorderFactory.createEmptyBorder(8, 12, 8, 12)));
            typeLabel.setBackground(new Color(248, 249, 250));
            typeLabel.setOpaque(true);
            contentPanel.add(typeLabel, gbc);

            // 开始日期
            gbc.gridx = 0;
            gbc.gridy = 2;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            contentPanel.add(createStyledLabel("开始日期 *"), gbc);
            gbc.gridx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            JTextField startDateField = createStyledTextField(30);
            startDateField.setText(promotion.getStartDate().toString());
            contentPanel.add(startDateField, gbc);

            // 结束日期
            gbc.gridx = 0;
            gbc.gridy = 3;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            contentPanel.add(createStyledLabel("结束日期 *"), gbc);
            gbc.gridx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            JTextField endDateField = createStyledTextField(30);
            endDateField.setText(promotion.getEndDate().toString());
            contentPanel.add(endDateField, gbc);

            // 右列
            // 折扣参数
            gbc.gridx = 2;
            gbc.gridy = 0;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            String discountLabelText = "折扣参数:";
            String discountValue = "";
            if ("DISCOUNT".equals(promotion.getPromotionType()) && promotion.getDiscountRate() != null) {
                discountLabelText = "折扣率(%) *";
                discountValue = promotion.getDiscountRate().toString();
            } else if ("FIXED_AMOUNT".equals(promotion.getPromotionType()) && promotion.getDiscountAmount() != null) {
                discountLabelText = "立减金额 *";
                discountValue = promotion.getDiscountAmount().toString();
            }
            contentPanel.add(createStyledLabel(discountLabelText), gbc);
            gbc.gridx = 3;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            JTextField discountField = createStyledTextField(30);
            discountField.setText(discountValue);
            contentPanel.add(discountField, gbc);

            // 最小购买数量
            gbc.gridx = 2;
            gbc.gridy = 1;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            contentPanel.add(createStyledLabel("最小购买数量"), gbc);
            gbc.gridx = 3;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            JSpinner quantitySpinner = createStyledSpinner();
            quantitySpinner.setModel(new SpinnerNumberModel(promotion.getMinQuantity(), 1, 999, 1));
            contentPanel.add(quantitySpinner, gbc);

            mainPanel.add(contentPanel, BorderLayout.CENTER);

            // 按钮面板
            JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 0));
            buttonPanel.setBackground(new Color(248, 249, 250));
            buttonPanel.setBorder(BorderFactory.createEmptyBorder(20, 0, 20, 0));

            JButton saveButton = createStyledButton("保存", new Color(40, 167, 69));
            JButton cancelButton = createStyledButton("取消", new Color(108, 117, 125));

            saveButton.addActionListener(e -> {
                if (updatePromotion(promotion, nameField, startDateField, endDateField, discountField,
                        quantitySpinner)) {
                    dialog.dispose();
                    loadPromotionData(); // 重新加载数据
                }
            });

            cancelButton.addActionListener(e -> dialog.dispose());

            buttonPanel.add(saveButton);
            buttonPanel.add(cancelButton);
            mainPanel.add(buttonPanel, BorderLayout.SOUTH);

            dialog.add(mainPanel);
            dialog.setVisible(true);

        } catch (Exception e) {
            showError("打开编辑对话框失败：" + e.getMessage());
        }
    }

    /**
     * 更新促销活动
     */
    private boolean updatePromotion(Promotion promotion, JTextField nameField,
            JTextField startDateField, JTextField endDateField,
            JTextField discountField, JSpinner quantitySpinner) {
        try {
            // 验证输入
            String name = nameField.getText().trim();
            String startDateStr = startDateField.getText().trim();
            String endDateStr = endDateField.getText().trim();
            String discountStr = discountField.getText().trim();
            int minQuantity = (Integer) quantitySpinner.getValue();

            if (name.isEmpty() || startDateStr.isEmpty() || endDateStr.isEmpty() || discountStr.isEmpty()) {
                showError("请填写所有必填字段！");
                return false;
            }

            // 更新促销对象
            promotion.setPromotionName(name);
            promotion.setMinQuantity(minQuantity);

            // 设置日期
            try {
                promotion.setStartDate(java.sql.Date.valueOf(startDateStr));
                promotion.setEndDate(java.sql.Date.valueOf(endDateStr));
            } catch (IllegalArgumentException e) {
                showError("日期格式不正确，请使用格式：YYYY-MM-DD");
                return false;
            }

            // 设置折扣参数
            try {
                BigDecimal discountValue = new BigDecimal(discountStr);
                if ("DISCOUNT".equals(promotion.getPromotionType())) {
                    if (discountValue.compareTo(BigDecimal.ZERO) <= 0 ||
                            discountValue.compareTo(new BigDecimal("100")) > 0) {
                        showError("折扣率必须在0-100之间！");
                        return false;
                    }
                    promotion.setDiscountRate(discountValue);
                } else if ("FIXED_AMOUNT".equals(promotion.getPromotionType())) {
                    if (discountValue.compareTo(BigDecimal.ZERO) <= 0) {
                        showError("立减金额必须大于0！");
                        return false;
                    }
                    promotion.setDiscountAmount(discountValue);
                }
            } catch (NumberFormatException e) {
                showError("折扣参数格式不正确！");
                return false;
            }

            // 保存到数据库
            if (promotionDAO.updatePromotion(promotion)) {
                showInfo("促销活动更新成功！");
                return true;
            } else {
                showError("促销活动更新失败，请检查数据库连接！");
                return false;
            }

        } catch (Exception e) {
            showError("更新促销活动失败：" + e.getMessage());
            return false;
        }
    }

    /**
     * 删除促销活动
     */
    private void deletePromotion(int selectedRow) {
        try {
            int promotionId = (Integer) promotionTableModel.getValueAt(selectedRow, 0);
            String promotionName = (String) promotionTableModel.getValueAt(selectedRow, 2);

            int confirm = JOptionPane.showConfirmDialog(this,
                    "确定要删除促销活动 \"" + promotionName + "\" 吗？\n注意：删除后将无法恢复！",
                    "确认删除", JOptionPane.YES_NO_OPTION);

            if (confirm == JOptionPane.YES_OPTION) {
                if (promotionDAO.deletePromotion(promotionId)) {
                    showInfo("促销活动删除成功！");
                    loadPromotionData(); // 重新加载数据
                } else {
                    showError("促销活动删除失败，请检查数据库连接！");
                }
            }
        } catch (Exception e) {
            showError("删除促销活动失败：" + e.getMessage());
        }
    }

    /**
     * 启动促销活动
     */
    private void startPromotion(int selectedRow) {
        try {
            int promotionId = (Integer) promotionTableModel.getValueAt(selectedRow, 0);
            String promotionName = (String) promotionTableModel.getValueAt(selectedRow, 2);
            String currentStatus = (String) promotionTableModel.getValueAt(selectedRow, 7);

            if ("进行中".equals(currentStatus)) {
                showInfo("促销活动已经在进行中！");
                return;
            }

            int confirm = JOptionPane.showConfirmDialog(this,
                    "确定要启动促销活动 \"" + promotionName + "\" 吗？",
                    "确认启动", JOptionPane.YES_NO_OPTION);

            if (confirm == JOptionPane.YES_OPTION) {
                if (promotionDAO.updatePromotionStatus(promotionId, "ACTIVE")) {
                    showInfo("促销活动启动成功！");
                    loadPromotionData(); // 重新加载数据
                } else {
                    showError("促销活动启动失败，请检查数据库连接！");
                }
            }
        } catch (Exception e) {
            showError("启动促销活动失败：" + e.getMessage());
        }
    }

    /**
     * 停止促销活动
     */
    private void stopPromotion(int selectedRow) {
        try {
            int promotionId = (Integer) promotionTableModel.getValueAt(selectedRow, 0);
            String promotionName = (String) promotionTableModel.getValueAt(selectedRow, 2);
            String currentStatus = (String) promotionTableModel.getValueAt(selectedRow, 7);

            if (!"进行中".equals(currentStatus)) {
                showInfo("只能停止正在进行中的促销活动！");
                return;
            }

            int confirm = JOptionPane.showConfirmDialog(this,
                    "确定要停止促销活动 \"" + promotionName + "\" 吗？",
                    "确认停止", JOptionPane.YES_NO_OPTION);

            if (confirm == JOptionPane.YES_OPTION) {
                if (promotionDAO.updatePromotionStatus(promotionId, "CANCELLED")) {
                    showInfo("促销活动停止成功！");
                    loadPromotionData(); // 重新加载数据
                } else {
                    showError("促销活动停止失败，请检查数据库连接！");
                }
            }
        } catch (Exception e) {
            showError("停止促销活动失败：" + e.getMessage());
        }
    }

    /**
     * 加载用户数据
     */
    private void loadUserData() {
        try {
            // 从数据库加载用户数据
            List<User> users = userDAO.getAllUsers();

            // 清空表格
            userTableModel.setRowCount(0);

            // 添加用户数据到表格
            for (User user : users) {
                Object[] row = {
                        user.getId(),
                        user.getUsername(),
                        user.getRealName(),
                        user.getRoleName() != null ? user.getRoleName() : "未知",
                        user.getPhone() != null ? user.getPhone() : "",
                        user.getEmail() != null ? user.getEmail() : "",
                        "ACTIVE".equals(user.getStatus()) ? "正常" : "禁用",
                        user.getCreatedAt() != null ? user.getCreatedAt().toString() : ""
                };
                userTableModel.addRow(row);
            }
        } catch (Exception e) {
            showError("加载用户数据失败：" + e.getMessage());
            // 如果数据库加载失败，使用示例数据
            addSampleUserData(userTableModel);
        }
    }

    /**
     * 添加示例用户数据
     */
    private void addSampleUserData(DefaultTableModel model) {
        // 示例用户数据
        Object[][] sampleData = {
                { 1, "admin", "系统管理员", "管理员", "13800138000", "admin@supermarket.com", "正常", "2024-01-01",
                        "2024-11-01 09:30" },
                { 2, "cashier01", "张小丽", "收银员", "13800138001", "cashier01@supermarket.com", "正常", "2024-01-15",
                        "2024-11-01 08:45" },
                { 3, "cashier02", "王小明", "收银员", "13800138002", "cashier02@supermarket.com", "正常", "2024-02-01",
                        "2024-10-31 17:30" },
                { 4, "manager01", "李经理", "管理员", "13800138003", "manager01@supermarket.com", "正常", "2024-01-10",
                        "2024-10-30 14:20" },
                { 5, "cashier03", "赵小红", "收银员", "13800138004", "cashier03@supermarket.com", "禁用", "2024-03-01",
                        "2024-10-25 16:00" }
        };

        for (Object[] row : sampleData) {
            model.addRow(row);
        }
    }

    /**
     * 设置用户管理事件监听器
     */
    private void setupUserManagementEventListeners(JButton editBtn, JButton deleteBtn,
            JButton resetBtn, JButton toggleBtn, JButton refreshBtn, JTable table,
            JButton searchBtn, JTextField searchField, JComboBox<String> roleFilter, JComboBox<String> statusFilter) {

        // 编辑用户
        editBtn.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow >= 0) {
                showEditUserDialog(selectedRow, table);
            } else {
                showInfo("请选择要编辑的用户");
            }
        });

        // 删除用户
        deleteBtn.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow >= 0) {
                deleteUser(selectedRow);
            } else {
                showInfo("请选择要删除的用户");
            }
        });

        // 重置密码
        resetBtn.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow >= 0) {
                resetUserPassword(selectedRow, table);
            } else {
                showInfo("请选择要重置密码的用户");
            }
        });

        // 启用/禁用用户
        toggleBtn.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow >= 0) {
                toggleUserStatus(selectedRow, table);
            } else {
                showInfo("请选择要更改状态的用户");
            }
        });

        // 刷新用户数据
        refreshBtn.addActionListener(e -> loadUserData());

        // 搜索用户
        searchBtn.addActionListener(e -> filterUsers(searchField.getText(), roleFilter.getSelectedItem().toString(),
                statusFilter.getSelectedItem().toString()));
        searchField.addActionListener(e -> filterUsers(searchField.getText(), roleFilter.getSelectedItem().toString(),
                statusFilter.getSelectedItem().toString()));

        // 筛选器变化时自动筛选
        roleFilter.addActionListener(e -> filterUsers(searchField.getText(), roleFilter.getSelectedItem().toString(),
                statusFilter.getSelectedItem().toString()));
        statusFilter.addActionListener(e -> filterUsers(searchField.getText(), roleFilter.getSelectedItem().toString(),
                statusFilter.getSelectedItem().toString()));
    }

    /**
     * 显示编辑用户对话框
     */
    private void showEditUserDialog(int selectedRow, JTable table) {
        try {
            String username = table.getValueAt(selectedRow, 1).toString();

            // 从数据库获取用户详细信息
            User user = userDAO.getUserByUsername(username);
            if (user == null) {
                showError("获取用户信息失败！");
                return;
            }

            // 创建编辑对话框 - 使用单列布局
            JDialog dialog = createStyledDialog("编辑用户", 500, 600);

            // 主面板
            JPanel mainPanel = new JPanel(new BorderLayout());
            mainPanel.setBackground(new Color(248, 249, 250));

            // 标题面板
            JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
            titlePanel.setBackground(new Color(248, 249, 250));
            JLabel titleLabel = new JLabel("编辑用户", JLabel.CENTER);
            titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 18));
            titleLabel.setForeground(new Color(52, 144, 220));
            titlePanel.add(titleLabel);
            mainPanel.add(titlePanel, BorderLayout.NORTH);

            // 内容面板 - 使用单列布局
            JPanel contentPanel = new JPanel(new GridBagLayout());
            contentPanel.setBackground(Color.WHITE);
            contentPanel.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                    BorderFactory.createEmptyBorder(30, 30, 30, 30)));

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(10, 15, 10, 15);
            gbc.anchor = GridBagConstraints.WEST;

            // 用户名（只读）
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.fill = GridBagConstraints.NONE;
            contentPanel.add(createStyledLabel("用户名"), gbc);
            gbc.gridx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            JLabel usernameLabel = new JLabel(user.getUsername());
            usernameLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
            usernameLabel.setForeground(new Color(73, 80, 87));
            usernameLabel.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                    BorderFactory.createEmptyBorder(8, 12, 8, 12)));
            usernameLabel.setBackground(new Color(248, 249, 250));
            usernameLabel.setOpaque(true);
            contentPanel.add(usernameLabel, gbc);

            // 真实姓名
            gbc.gridx = 0;
            gbc.gridy = 1;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            contentPanel.add(createStyledLabel("真实姓名 *"), gbc);
            gbc.gridx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            JTextField realNameField = createStyledTextField(25);
            realNameField.setText(user.getRealName());
            contentPanel.add(realNameField, gbc);

            // 角色
            gbc.gridx = 0;
            gbc.gridy = 2;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            contentPanel.add(createStyledLabel("角色 *"), gbc);
            gbc.gridx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            JComboBox<String> roleCombo = createStyledComboBox();
            roleCombo.addItem("管理员");
            roleCombo.addItem("收银员");
            // 设置当前角色
            String currentRole = user.getRoleName() != null ? user.getRoleName() : "收银员";
            roleCombo.setSelectedItem(currentRole);
            contentPanel.add(roleCombo, gbc);

            // 电话
            gbc.gridx = 0;
            gbc.gridy = 3;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            contentPanel.add(createStyledLabel("电话 *"), gbc);
            gbc.gridx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            JTextField phoneField = createStyledTextField(25);
            phoneField.setText(user.getPhone() != null ? user.getPhone() : "");
            contentPanel.add(phoneField, gbc);

            // 邮箱
            gbc.gridx = 0;
            gbc.gridy = 4;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            contentPanel.add(createStyledLabel("邮箱 *"), gbc);
            gbc.gridx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            JTextField emailField = createStyledTextField(25);
            emailField.setText(user.getEmail() != null ? user.getEmail() : "");
            contentPanel.add(emailField, gbc);

            // 状态
            gbc.gridx = 0;
            gbc.gridy = 5;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            contentPanel.add(createStyledLabel("状态"), gbc);
            gbc.gridx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            JComboBox<String> statusCombo = createStyledComboBox();
            statusCombo.addItem("正常");
            statusCombo.addItem("禁用");
            statusCombo.setSelectedItem("ACTIVE".equals(user.getStatus()) ? "正常" : "禁用");
            contentPanel.add(statusCombo, gbc);

            mainPanel.add(contentPanel, BorderLayout.CENTER);

            // 按钮面板
            JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 0));
            buttonPanel.setBackground(new Color(248, 249, 250));
            buttonPanel.setBorder(BorderFactory.createEmptyBorder(20, 0, 20, 0));

            JButton saveButton = createStyledButton("保存", new Color(40, 167, 69));
            JButton cancelButton = createStyledButton("取消", new Color(108, 117, 125));

            saveButton.addActionListener(e -> {
                // 验证输入
                String realName = realNameField.getText().trim();
                String phone = phoneField.getText().trim();
                String email = emailField.getText().trim();
                String role = (String) roleCombo.getSelectedItem();
                String status = (String) statusCombo.getSelectedItem();

                if (realName.isEmpty() || phone.isEmpty() || email.isEmpty()) {
                    showError("请填写所有必填项");
                    return;
                }

                try {
                    // 更新用户信息
                    user.setRealName(realName);
                    user.setPhone(phone);
                    user.setEmail(email);
                    user.setStatus("正常".equals(status) ? "ACTIVE" : "INACTIVE");

                    // 确定角色ID
                    int roleId = "管理员".equals(role) ? 1 : 2;

                    // 更新到数据库
                    if (userDAO.updateUser(user, roleId)) {
                        showInfo("用户信息更新成功！");
                        dialog.dispose();
                        // 重新加载用户数据
                        loadUserData();
                    } else {
                        showError("用户信息更新失败！");
                    }
                } catch (Exception ex) {
                    showError("更新用户失败：" + ex.getMessage());
                }
            });

            cancelButton.addActionListener(e -> dialog.dispose());

            buttonPanel.add(saveButton);
            buttonPanel.add(cancelButton);
            mainPanel.add(buttonPanel, BorderLayout.SOUTH);

            dialog.add(mainPanel);
            dialog.setVisible(true);

        } catch (Exception e) {
            showError("打开编辑对话框失败：" + e.getMessage());
        }
    }

    /**
     * 删除用户
     */
    private void deleteUser(int selectedRow) {
        try {
            String username = userTableModel.getValueAt(selectedRow, 1).toString();
            String realName = userTableModel.getValueAt(selectedRow, 2).toString();

            // 不能删除当前登录用户
            if (username.equals(currentUser.getUsername())) {
                showError("不能删除当前登录的用户！");
                return;
            }

            int confirm = JOptionPane.showConfirmDialog(this,
                    "确定要删除用户 " + realName + " (" + username + ") 吗？\n此操作不可恢复！",
                    "确认删除",
                    JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);

            if (confirm == JOptionPane.YES_OPTION) {
                // 从数据库删除用户
                if (userDAO.deleteUser(username)) {
                    showInfo("用户删除成功！");
                    // 重新加载用户数据
                    loadUserData();
                } else {
                    showError("用户删除失败！");
                }
            }
        } catch (Exception e) {
            showError("删除用户失败：" + e.getMessage());
        }
    }

    /**
     * 重置用户密码
     */
    private void resetUserPassword(int selectedRow, JTable table) {
        try {
            String username = table.getValueAt(selectedRow, 1).toString();
            String realName = table.getValueAt(selectedRow, 2).toString();

            int confirm = JOptionPane.showConfirmDialog(this,
                    "确定要重置用户 " + realName + " (" + username + ") 的密码吗？\n重置后密码将为：123456",
                    "确认重置密码",
                    JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

            if (confirm == JOptionPane.YES_OPTION) {
                // 重置密码到数据库
                if (userDAO.resetPassword(username, "123456")) {
                    showInfo("密码重置成功！用户 " + username + " 的密码已重置为 123456");
                } else {
                    showError("密码重置失败！");
                }
            }
        } catch (Exception e) {
            showError("重置密码失败：" + e.getMessage());
        }
    }

    /**
     * 切换用户状态
     */
    private void toggleUserStatus(int selectedRow, JTable table) {
        try {
            String username = table.getValueAt(selectedRow, 1).toString();
            String realName = table.getValueAt(selectedRow, 2).toString();
            String currentStatus = table.getValueAt(selectedRow, 6).toString();
            String newStatus = "正常".equals(currentStatus) ? "禁用" : "正常";

            // 不能禁用当前登录用户
            if (username.equals(currentUser.getUsername()) && "禁用".equals(newStatus)) {
                showError("不能禁用当前登录的用户！");
                return;
            }

            int confirm = JOptionPane.showConfirmDialog(this,
                    "确定要将用户 " + realName + " (" + username + ") 的状态从 " + currentStatus + " 改为 " + newStatus + " 吗？",
                    "确认状态变更",
                    JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

            if (confirm == JOptionPane.YES_OPTION) {
                // 更新用户状态到数据库
                String newStatusValue = "正常".equals(newStatus) ? "ACTIVE" : "INACTIVE";
                if (userDAO.updateUserStatus(username, newStatusValue)) {
                    showInfo("用户状态更新成功！用户 " + username + " 的状态已改为 " + newStatus);
                    // 重新加载用户数据
                    loadUserData();
                } else {
                    showError("用户状态更新失败！");
                }
            }
        } catch (Exception e) {
            showError("更新用户状态失败：" + e.getMessage());
        }
    }

    /**
     * 搜索用户
     */
    private void searchUsers(String keyword) {
        try {
            if (keyword.trim().isEmpty()) {
                // 如果搜索关键词为空，重新加载所有用户数据
                loadUserData();
                return;
            }

            // 从数据库搜索用户
            List<User> users = userDAO.searchUsers(keyword);

            // 清空表格
            userTableModel.setRowCount(0);

            // 添加搜索结果
            for (User user : users) {
                Object[] row = {
                        user.getId(),
                        user.getUsername(),
                        user.getRealName(),
                        user.getRoleName() != null ? user.getRoleName() : "未知",
                        user.getPhone() != null ? user.getPhone() : "",
                        user.getEmail() != null ? user.getEmail() : "",
                        "ACTIVE".equals(user.getStatus()) ? "正常" : "禁用",
                        user.getCreatedAt() != null ? user.getCreatedAt().toString() : ""
                };
                userTableModel.addRow(row);
            }

            if (users.isEmpty()) {
                showInfo("未找到匹配的用户");
            } else {
                showInfo("找到 " + users.size() + " 个匹配的用户");
            }
        } catch (Exception e) {
            showError("搜索用户失败：" + e.getMessage());
        }
    }

    /**
     * 筛选用户（搜索+角色+状态）
     */
    private void filterUsers(String keyword, String role, String status) {
        try {
            // 从数据库获取所有用户
            List<User> allUsers = userDAO.getAllUsers();

            // 清空表格
            userTableModel.setRowCount(0);

            int count = 0;

            // 筛选用户
            for (User user : allUsers) {
                boolean matchesKeyword = keyword.trim().isEmpty() ||
                        user.getUsername().toLowerCase().contains(keyword.toLowerCase()) ||
                        user.getRealName().toLowerCase().contains(keyword.toLowerCase()) ||
                        (user.getPhone() != null && user.getPhone().contains(keyword)) ||
                        (user.getEmail() != null && user.getEmail().toLowerCase().contains(keyword.toLowerCase()));

                boolean matchesRole = "全部".equals(role) ||
                        ("管理员".equals(role) && "ADMIN".equals(user.getRoleName())) ||
                        ("收银员".equals(role) && "CASHIER".equals(user.getRoleName()));

                boolean matchesStatus = "全部".equals(status) ||
                        ("正常".equals(status) && "ACTIVE".equals(user.getStatus())) ||
                        ("禁用".equals(status) && "INACTIVE".equals(user.getStatus()));

                if (matchesKeyword && matchesRole && matchesStatus) {
                    Object[] row = {
                            user.getId(),
                            user.getUsername(),
                            user.getRealName(),
                            user.getRoleName() != null ? user.getRoleName() : "未知",
                            user.getPhone() != null ? user.getPhone() : "",
                            user.getEmail() != null ? user.getEmail() : "",
                            "ACTIVE".equals(user.getStatus()) ? "正常" : "禁用",
                            user.getCreatedAt() != null ? user.getCreatedAt().toString() : ""
                    };
                    userTableModel.addRow(row);
                    count++;
                }
            }

            if (count == 0) {
                showInfo("未找到匹配的用户");
            } else {
                showInfo("找到 " + count + " 个匹配的用户");
            }
        } catch (Exception e) {
            showError("筛选用户失败：" + e.getMessage());
        }
    }

    /**
     * 显示临期商品审批对话框
     */
    private void showExpiringProductApprovalDialog() {
        JDialog dialog = createStyledDialog("临期商品审批", 1200, 800);

        // 主面板
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBackground(new Color(248, 249, 250));

        // 标题面板
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        titlePanel.setBackground(new Color(248, 249, 250));
        JLabel titleLabel = new JLabel("临期商品审批管理", JLabel.CENTER);
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 18));
        titleLabel.setForeground(new Color(52, 144, 220));
        titlePanel.add(titleLabel);
        mainPanel.add(titlePanel, BorderLayout.NORTH);

        // 操作面板
        JPanel operationPanel = createStyledPanel();
        operationPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));

        JComboBox<String> statusFilter = createStyledComboBox();
        statusFilter.addItem("全部");
        statusFilter.addItem("待审批");
        statusFilter.addItem("已批准");
        statusFilter.addItem("已拒绝");
        statusFilter.addItem("已处理");

        JButton refreshButton = createStyledButton("刷新", new Color(74, 144, 226));
        JButton approveButton = createStyledButton("批准", new Color(40, 167, 69));
        JButton rejectButton = createStyledButton("拒绝", new Color(220, 53, 69));

        operationPanel.add(new JLabel("状态筛选："));
        operationPanel.add(statusFilter);
        operationPanel.add(refreshButton);
        operationPanel.add(approveButton);
        operationPanel.add(rejectButton);

        // 内容面板
        JPanel contentPanel = new JPanel(new BorderLayout());
        contentPanel.setBackground(Color.WHITE);
        contentPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                BorderFactory.createEmptyBorder(20, 20, 20, 20)));

        // 创建临期商品审批表格
        String[] columns = { "申报ID", "商品编码", "商品名称", "当前库存", "到期日期", "建议处理", "折扣率", "状态", "申报人", "申报日期", "审批人",
                "处理日期" };
        DefaultTableModel expiringModel = new DefaultTableModel(columns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        JTable expiringTable = createStyledTable(expiringModel);
        expiringTable.setRowHeight(35);
        expiringTable.getTableHeader().setFont(new Font("Microsoft YaHei", Font.BOLD, 13));
        expiringTable.getTableHeader().setBackground(new Color(52, 144, 220));
        expiringTable.getTableHeader().setForeground(Color.WHITE);

        // 设置表格默认文字颜色为黑色
        expiringTable.setDefaultRenderer(Object.class, (table, value, isSelected, hasFocus, row, column) -> {
            JLabel label = new JLabel(value != null ? value.toString() : "");
            label.setOpaque(true);
            label.setForeground(Color.BLACK);
            if (isSelected) {
                label.setBackground(table.getSelectionBackground());
            } else {
                label.setBackground(Color.WHITE);
            }
            return label;
        });

        // 设置状态列的颜色渲染器
        expiringTable.getColumnModel().getColumn(7)
                .setCellRenderer((table, value, isSelected, hasFocus, row, column) -> {
                    JLabel label = new JLabel(value != null ? value.toString() : "");
                    label.setOpaque(true);
                    label.setHorizontalAlignment(JLabel.CENTER);
                    label.setForeground(Color.BLACK); // 设置所有文字为黑色

                    if (!isSelected) {
                        switch (value != null ? value.toString() : "") {
                            case "待审批":
                                label.setBackground(new Color(255, 243, 205));
                                break;
                            case "已批准":
                                label.setBackground(new Color(212, 237, 218));
                                break;
                            case "已拒绝":
                                label.setBackground(new Color(248, 215, 218));
                                break;
                            case "已处理":
                                label.setBackground(new Color(209, 236, 241));
                                break;
                            default:
                                label.setBackground(Color.WHITE);
                        }
                    } else {
                        label.setBackground(table.getSelectionBackground());
                        label.setForeground(Color.BLACK); // 选中时也保持黑色文字
                    }

                    return label;
                });

        // 加载临期商品申报数据
        loadExpiringProductData(expiringModel);

        JScrollPane scrollPane = new JScrollPane(expiringTable);
        scrollPane.setBorder(BorderFactory.createLineBorder(new Color(220, 220, 220), 1));
        contentPanel.add(scrollPane, BorderLayout.CENTER);

        mainPanel.add(operationPanel, BorderLayout.NORTH);
        mainPanel.add(contentPanel, BorderLayout.CENTER);

        // 设置事件监听器
        refreshButton.addActionListener(e -> loadExpiringProductData(expiringModel));

        statusFilter.addActionListener(e -> {
            String selectedStatus = (String) statusFilter.getSelectedItem();
            filterExpiringProducts(expiringModel, selectedStatus);
        });

        approveButton.addActionListener(e -> {
            int selectedRow = expiringTable.getSelectedRow();
            if (selectedRow >= 0) {
                int id = (Integer) expiringModel.getValueAt(selectedRow, 0);
                String currentStatus = (String) expiringModel.getValueAt(selectedRow, 7);
                if ("待审批".equals(currentStatus)) {
                    approveExpiringProduct(id, "APPROVED", expiringModel);
                } else {
                    showInfo("只能审批状态为'待审批'的申报");
                }
            } else {
                showInfo("请选择要审批的申报记录");
            }
        });

        rejectButton.addActionListener(e -> {
            int selectedRow = expiringTable.getSelectedRow();
            if (selectedRow >= 0) {
                int id = (Integer) expiringModel.getValueAt(selectedRow, 0);
                String currentStatus = (String) expiringModel.getValueAt(selectedRow, 7);
                if ("待审批".equals(currentStatus)) {
                    String reason = JOptionPane.showInputDialog(dialog, "请输入拒绝原因：", "拒绝审批",
                            JOptionPane.QUESTION_MESSAGE);
                    if (reason != null && !reason.trim().isEmpty()) {
                        approveExpiringProduct(id, "REJECTED", expiringModel, reason);
                    }
                } else {
                    showInfo("只能审批状态为'待审批'的申报");
                }
            } else {
                showInfo("请选择要拒绝的申报记录");
            }
        });

        dialog.add(mainPanel);
        dialog.setVisible(true);
    }

    /**
     * 加载临期商品申报数据
     */
    private void loadExpiringProductData(DefaultTableModel model) {
        try {
            model.setRowCount(0);
            var expiringProducts = expiringProductDAO.getAllExpiringProducts();

            for (var product : expiringProducts) {
                Object[] row = {
                        product.getId(),
                        product.getProductCode(),
                        product.getProductName(),
                        product.getCurrentStock(),
                        product.getExpiryDate(),
                        product.getSuggestedActionText(),
                        product.getDiscountRate() != null ? product.getDiscountRate() + "%" : "",
                        product.getStatusText(),
                        product.getReporterName(),
                        product.getReportDate(),
                        product.getApproverName() != null ? product.getApproverName() : "",
                        product.getProcessedDate() != null ? product.getProcessedDate() : ""
                };
                model.addRow(row);
            }
        } catch (Exception e) {
            showError("加载临期商品申报数据失败：" + e.getMessage());
        }
    }

    /**
     * 筛选临期商品申报数据
     */
    private void filterExpiringProducts(DefaultTableModel model, String status) {
        try {
            model.setRowCount(0);

            List<com.supermarket.model.ExpiringProduct> expiringProducts;
            if ("全部".equals(status)) {
                expiringProducts = expiringProductDAO.getAllExpiringProducts();
            } else {
                String dbStatus = convertStatusToDb(status);
                expiringProducts = expiringProductDAO.getExpiringProductsByStatus(dbStatus);
            }

            for (var product : expiringProducts) {
                Object[] row = {
                        product.getId(),
                        product.getProductCode(),
                        product.getProductName(),
                        product.getCurrentStock(),
                        product.getExpiryDate(),
                        product.getSuggestedActionText(),
                        product.getDiscountRate() != null ? product.getDiscountRate() + "%" : "",
                        product.getStatusText(),
                        product.getReporterName(),
                        product.getReportDate(),
                        product.getApproverName() != null ? product.getApproverName() : "",
                        product.getProcessedDate() != null ? product.getProcessedDate() : ""
                };
                model.addRow(row);
            }
        } catch (Exception e) {
            showError("筛选临期商品申报数据失败：" + e.getMessage());
        }
    }

    /**
     * 审批临期商品申报
     */
    private void approveExpiringProduct(int id, String status, DefaultTableModel model) {
        approveExpiringProduct(id, status, model, null);
    }

    /**
     * 审批临期商品申报（带备注）
     */
    private void approveExpiringProduct(int id, String status, DefaultTableModel model, String remarks) {
        try {
            if (expiringProductDAO.approveExpiringProduct(id, currentUser.getId(), status, remarks)) {
                String action = "APPROVED".equals(status) ? "批准" : "拒绝";
                showInfo("临期商品申报" + action + "成功！");
                loadExpiringProductData(model); // 重新加载数据
            } else {
                showError("审批操作失败！");
            }
        } catch (Exception e) {
            showError("审批失败：" + e.getMessage());
        }
    }

    /**
     * 导出销售报表
     */
    private void exportSalesReport(String period, List<Object[]> statistics, BigDecimal totalAmount) {
        try {
            // 创建文件选择器
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setDialogTitle("导出销售报表");
            fileChooser.setSelectedFile(new java.io.File("销售报表_" + period + "_" +
                    java.time.LocalDate.now().toString() + ".txt"));

            int result = fileChooser.showSaveDialog(this);
            if (result == JFileChooser.APPROVE_OPTION) {
                java.io.File file = fileChooser.getSelectedFile();

                // 生成报表内容
                StringBuilder report = new StringBuilder();
                report.append("超市管理系统 - 销售报表\n");
                report.append("=".repeat(50)).append("\n");
                report.append("统计期间：").append(period).append("\n");
                report.append("生成时间：").append(java.time.LocalDateTime.now().toString()).append("\n");
                report.append("=".repeat(50)).append("\n\n");

                // 统计概览
                int totalOrders = statistics.stream().mapToInt(stat -> ((Number) stat[2]).intValue()).sum();
                BigDecimal totalDiscount = statistics.stream()
                        .map(stat -> (BigDecimal) stat[4])
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal avgOrderAmount = totalOrders > 0
                        ? totalAmount.divide(new BigDecimal(totalOrders), 2, java.math.RoundingMode.HALF_UP)
                        : BigDecimal.ZERO;

                report.append("统计概览：\n");
                report.append("-".repeat(30)).append("\n");
                report.append("总销售额：¥").append(String.format("%.2f", totalAmount)).append("\n");
                report.append("总订单数：").append(totalOrders).append("\n");
                report.append("平均订单金额：¥").append(String.format("%.2f", avgOrderAmount)).append("\n");
                report.append("总折扣金额：¥").append(String.format("%.2f", totalDiscount)).append("\n");
                report.append("收银员数量：").append(statistics.size()).append("\n\n");

                // 收银员业绩详情
                report.append("收银员业绩详情：\n");
                report.append("-".repeat(30)).append("\n");
                report.append(String.format("%-10s %-8s %-12s %-12s %-12s %-12s\n",
                        "收银员", "订单数", "销售额", "折扣金额", "实收金额", "平均订单金额"));
                report.append("-".repeat(80)).append("\n");

                for (Object[] stat : statistics) {
                    report.append(String.format("%-10s %-8d %-12s %-12s %-12s %-12s\n",
                            stat[1], // 收银员姓名
                            stat[2], // 订单数
                            "¥" + String.format("%.2f", (BigDecimal) stat[3]), // 销售额
                            "¥" + String.format("%.2f", (BigDecimal) stat[4]), // 折扣金额
                            "¥" + String.format("%.2f", (BigDecimal) stat[5]), // 实收金额
                            "¥" + String.format("%.2f", (BigDecimal) stat[6]) // 平均订单金额
                    ));
                }

                report.append("\n").append("=".repeat(50)).append("\n");
                report.append("报表生成完成");

                // 写入文件
                try (java.io.FileWriter writer = new java.io.FileWriter(file,
                        java.nio.charset.StandardCharsets.UTF_8)) {
                    writer.write(report.toString());
                }

                showInfo("销售报表已成功导出到：" + file.getAbsolutePath());
            }
        } catch (Exception ex) {
            showError("导出报表失败：" + ex.getMessage());
        }
    }
}
